Dylan Czenski
Dylan Czenski

Reputation: 1365

Count amount of words in a string without any loops

For example you send a string "Yo what’s up dog?" to a function, the function returns 4 counts.

below is what I wrote:

public class CountString {
    public int count(String str){
        int count=0;
        for(int i=0; i<str.length();i++){
            if(str.charAt(i) == ' ')
                count++;
        }
        System.out.printf("\n number of strings: "+ (count+1));
        return count+1;
    }
}

Are there any other faster methods? Now how do you perform the same job without including any loops (for, while, do-while)?

Upvotes: 0

Views: 1951

Answers (2)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Without loop! -

One way using String#split

  1. split the string with ' ' (space)
  2. get the Word count

Code snippet -

return str.trim().split(" ");

One other way is using StringTokenizer -

 StringTokenizer st = new StringTokenizer(str); // default delimiter is space
 return st.countTokens();

Upvotes: 1

thegauravmahawar
thegauravmahawar

Reputation: 2823

You could do:

String s = "Yo what’s up dog?";
String[] arr = s.split(" ");
System.out.println(arr.length); //prints 4

Upvotes: 2

Related Questions