我的字符串是这样的
String myString= "3:2 2:26 1:11 8:4 4:25";
在此字符串中,我想添加“:”之后(以及下一个空格之前)出现的所有数字。在本例中,结果为 2+26+11+4+25 = 68。如何使用 Reg 表达式实现此目的?
我的努力是:
if(a.contains(":")){
for(int i=0; i<a.length(); i++) {
if(a.contains(":")){
int indexOFColan= a.indexOf(":");
//System.out.println("indexOFColan:"+indexOFColan);
//int indexWhiteSpace = a.indexOf(" ");
String firstValue = String.valueOf(a.charAt((indexOFColan+1)));
System.out.println("FinalString:"+firstValue);
}
}
}
最佳答案
对我有用。
String in = "3:2 2:26 1:11 8:4 4:25";
String[] split = in.split(" ");
int sum = 0;
for(int i = 0; i < split.length; i++)
{
try {
sum += Integer.parseInt(split[i].split(":")[1]);
} catch(NumberFormatException e) {
System.out.println("Input not a number");
}
}
System.out.println(sum);
关于java - 如何在java中分割复杂字符串以及如何对值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641152/