Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word count on Java

Tags:

java

for-loop

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.

like image 526
Oshrib Avatar asked Jun 12 '26 05:06

Oshrib


1 Answers

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
like image 85
aioobe Avatar answered Jun 13 '26 18:06

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!