【发布时间】:2010-10-06 11:11:06
【问题描述】:
我想提取数字并使用 Java 添加这些数字,字符串保持不变。
字符串形式-
String msg="1,2,hello,world,3,4";
输出应该像 - 10,hello,world
谢谢
【问题讨论】:
-
全部用逗号分隔?
-
我相信正则表达式可以解决问题。
标签: java
我想提取数字并使用 Java 添加这些数字,字符串保持不变。
字符串形式-
String msg="1,2,hello,world,3,4";
输出应该像 - 10,hello,world
谢谢
【问题讨论】:
标签: java
解决你的问题:
【讨论】:
String pieces[] = msg.split(",");
int sum=0;
StringBuffer sb = new StringBuffer();
for(int i=0;i < pieces.length;i++){
if(org.apache.commons.lang.math.NumberUtils.isNumber(pieces[i])){
sb.appendpieces[i]();
}else{
int i = Integer.parseInt(pieces[i]));
sum+=i;
}
}
System.out.println(sum+","+sb.);
}
【讨论】:
String[] parts = msg.split(",");
int sum = 0;
StringBuilder stringParts = new StringBuilder();
for (String part : parts) {
try {
sum += Integer.parseInt(part);
} catch (NumberFormatException ex) {
stringParts.append("," + part);
}
}
stringParts.insert(0, String.valueOf(sum));
System.out.println(stringParts.toString()); // the final result
请注意,上述使用异常作为控制流的做法几乎总是应避免。这个具体案例我相信是个例外,因为没有方法可以验证字符串的“可解析性”。如果有Integer.isNumber(string),那么这就是要走的路。实际上,您可以创建这样的实用方法。检查this question。
【讨论】:
这是一个非常简单的正则表达式版本:
/**
* Use a constant pattern to skip expensive recompilation.
*/
private static final Pattern INT_PATTERN = Pattern.compile("\\d+",
Pattern.DOTALL);
public static int addAllIntegerOccurrences(final String input){
int result = 0;
if(input != null){
final Matcher matcher = INT_PATTERN.matcher(input);
while(matcher.find()){
result += Integer.parseInt(matcher.group());
}
}
return result;
}
测试代码:
public static void main(final String[] args){
System.out.println(addAllIntegerOccurrences("1,2,hello,world,3,4"));
}
输出:
10
注意事项:
如果数字加起来大于Integer.Max_VALUE,这显然不起作用。
【讨论】: