Reputation: 1365
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
Reputation: 41200
Without loop! -
One way using String#split
' '
(space) 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
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