我最近被要求用 java 编写一个函数,它将字符串中的数字(不是数字)相加。例如如果字符串是 abc35zz400tt15,输出应该是 450。
这是我写的:
public static void getSum(String a){
String[] arr=a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
int sum=0;
for(int i=0;i<arr.length;i++){
if(Pattern.matches("[0-9]+", arr[i]))
sum+=Integer.parseInt(arr[i]);
}
System.out.println(sum);
}
是否有更有效的方法来执行此操作,因为他们看起来对上述代码不满意。
最佳答案
我认为一次只搜索一个模式会更简单一些,而不是拆分字符串。
Pattern pattern = Pattern.compile("[0-9]+"); //or you can use \\d if you want
Matcher matcher = pattern.matcher(a);
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
关于java - 打印字符串中数字(不是数字)的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487340/