从字符串中提取整数并将其添加到Java中 [英] Extract integers from string and add them in Java
本文介绍了从字符串中提取整数并将其添加到Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中提取整数并添加它们.
I want to extract the integers from string and add them.
Ex:
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屋!
查看全文