You may start with replacing all non-numbers from the string
with space
, and spilt
it based on the 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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…