Sourav Das Sourav Das - 23 days ago 6
Java Question

Count Integer Words from Sentences

I have a Sentence which contains like "Count 225989 the 20124 integer 20124 122 words"

I want to Count the total number of Integer Words from it.
Like Above string contains 4 integer words of 225989 , 20124 , 20124 , 122.
Please help me with this..

I just tried split the words

String str ="Sentences";
List<String> myList = new ArrayList<>(Arrays.asList(str.split(" ")));

Answer

Here is a solution using ascii code to detect if character is a number.

// main program
String str = "Count 225989 the 20124 integer 20124 122 words"
String[] splitted = str.split(" ");
for (String s : splitted){
    if(isNumber(s))
         System.out.println(s);
}

public boolean isNumber(String s){
    for (char c : s.toCharArray()){
        if(c<48 || c>57){
            return false;
        }
    }
    return true;
}