我有一个字符串:“我有22根香蕉,121支铅笔和p32苹果”。
如何编写代码,使其返回字符串中出现的数字?
(在本例中它应该输出3,因为有3个数字)
注:数字被定义为连续的数字序列,中间没有任何中断。
公共int countNums() { ...implement }
发布于 2018-06-01 03:09:32
您可以使用如下代码。
public class Main {
public static void main(String[] args) {
String s = "I have 22 bananas , 121 pencils, and 32 apples";
String[] sarr = s.split(" ");
int count = 0;
for(String str : sarr) {
try {
Integer.parseInt(str);
} catch(NumberFormatException e) {
count++;
}
}
System.out.println(sarr.length - count);
}
}
如果数字是小数,则使用double而不是Integer。
发布于 2018-06-01 03:20:45
你可以试试这个,对我很管用。
public static void main(String[]args){
String str = "I have 22 bananas , 121 pencils12, and 32 apples";
str = str.replaceAll("[^0-9]+", " ");// numbers separated by spaces
int o=str.trim().split(" ").length;// turn it to array and count the length
System.out.println(o);
}
}
https://stackoverflow.com/questions/50630891
复制相似问题