I tried below but i dot recognise substring which contains character or integer..
String abc="12 abc 7 4";
String str[]=abc.split(" ");
I tried below but i dot recognise substring which contains character or integer..
String abc="12 abc 7 4";
String str[]=abc.split(" ");
I suggest using regular expressions in order to extract the numbers:
String abc = "12 abc 7 4";
Matcher m = Pattern.compile("[0-9]+").matcher(abc);
int sum = 0;
while (m.find())
sum += Integer.parseInt(m.group());
// 23 == 12 + 7 + 4
System.out.print(sum);
You can use bellow snippet as well,
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);
Please try this