How can I count the words of a sentence given as string? We are allowed to use only the following: for loops, if statemant, while, charAt, length().
I wrote this code:
public static int getWordCount()
{
String data = "bla bla bla bla";
int Count = 0;
for (int i=0; i<data.length(); i++)
{
if (data.charAt(i) != ' ')
Count ++;
}
return Count;
}
But it counts only the letters and not the words.
Here’s a suggestion: Count the number of
' 'and add 1?Example:
If you want to get fancy you could keep a boolean variable named something like
lastWasSpace, set it to true when running into a space, setting it to false when you run into a non-space character. If you only increment theCountwhenlastWasSpaceis false, you’ll be able to handle strings with multiple consecutive spaces as well.