我想编写一个名为 printDigit
的方法,该方法应该查找字符串中有多少个整数。
对于15 an1234d 16 man
,它应该返回2
。
这就是我绝望的代码:)
public String printDigit() {
String input = "15 an1234d 16 man";
int len = input.split(" ").length;
return len + "";
}
返回 3
,它不应该将 an1234d
算作整数。
最佳答案
您可以使用正则表达式:
(^|\s)\d+(\s|$)
这意味着:任意数量的数字,前面有一个空格(或字符串的开头),后面有一个空格(或字符串的结尾)。
这是一个演示在 Java 中使用的代码片段。您可以运行 demo of this code online here .
public String printDigit() {
String input = "15 an1234d 16 man";
Pattern p = Pattern.compile("(^|\\s)\\d+(\\s|$)");
Matcher m = p.matcher(input);
int numberCount = 0;
while(m.find()) {
numberCount++;
}
return Integer.toString(numberCount);
}
输出:
Numbers: 2
<小时/>
更新:根据评论,使用 parseInt()
的替代方案:
注意在这种情况下使用parseInt()
是coding by Exception (这被认为是一种不好的做法),但如果您必须使用它,下面是您可以使用的片段。 Run it online here .
public static String printDigit() {
String input = "15 an1234d 16 man";
String[] tokens = input.split(" ");
int numberCount = 0;
for(String s : tokens) {
try {
Integer.parseInt(s);
numberCount++;
} catch (Exception e) { /* couldnt parse as integer, do nothing */ }
}
return Integer.toString(numberCount);
}
输出:
Using parseInt(): 2
关于java - 在字符串中查找整数java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457184/