java程序返回参数String中找到的所有整数的总和

pre*_*eth 0 java

我想编写一个java程序来返回参数String中找到的所有整数的总和.例如,取一个字符串:"12 hi,8和9"现在答案是12 + 8 + 9 = 29.但我真的不知道甚至如何开始可以任何人帮助!

Bab*_*aby 5

您可以从替换所有非数字开始string使用space,并且spilt它的基础上的space

String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
    try{
        sum+=Integer.parseInt(numbers[i]);
    }
    catch( Exception e ) {
      //Just in case, the element in the array is not parse-able into Integer, Ignore it
    }
}
System.out.println("The sum is:"+sum);
Run Code Online (Sandbox Code Playgroud)