从字符串中提取整数并将它们添加到 Java 中 [英] Extract integers from string and add them in Java
本文介绍了从字符串中提取整数并将它们添加到 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中提取整数并添加它们.
I want to extract the integers from string and add them.
例如:
String s="ab34yuj789km2";
我应该从中得到整数的输出为 825(即 34 + 789 + 2 = 825 )
I should get the output of integers from it as 825 ( i.e., 34 + 789 + 2 = 825 )
推荐答案
这是一种方法,使用 String.split:
Here's one way, by using String.split:
public static void main(String[] args) {
String s="ab34yuj789km2";
int total = 0;
for(String numString : s.split("[^0-9]+")) {
if(!numString.isEmpty()) {
total += Integer.parseInt(numString);
}
}
// Print the result
System.out.println("Total = " + total);
}
注意模式 "[^0-9]+"
是一个正则表达式.它匹配一个或多个非十进制数字的字符.还有一个模式 \d
用于十进制数.
Note the pattern "[^0-9]+"
is a regular expression. It matches one or more characters that are not decimal numbers. There is also a pattern \d
for decimal numbers.
这篇关于从字符串中提取整数并将它们添加到 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文