-1

I tried below but i dot recognise substring which contains character or integer..

String abc="12 abc 7 4";
String str[]=abc.split(" ");
backtrack
  • 7,996
  • 5
  • 52
  • 99
Ajay
  • 21
  • 1
    Possible duplicate of http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java – Rahman Nov 28 '16 at 14:29
  • 2
    Try parsing each element in the array and look for an exception to be thrown when you parse a character(or a string) to an integer. – Tacolibre Nov 28 '16 at 14:30

2 Answers2

1

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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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

Kedar1442
  • 217
  • 2
  • 8