Issue
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.
Solution
Here's a suggestion: Count the number of ' '
and add 1?
Example:
"bla bla bla bla"
1 2 3 : 3 + 1 = 4
"hello"
: 0 + 1 = 1
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 the Count
when lastWasSpace
is false, you'll be able to handle strings with multiple consecutive spaces as well.
"bla bla bla"
1 2 : 2 + 1 = 3
lastWasSpace: FFFFTTTFFFFTTTTTFFFF
Answered By - aioobe
Answer Checked By - Clifford M. (JavaFixing Volunteer)