开发者

Word count on Java

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:

"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


the given code would indeed count letters and not words. You may want to change the condition to:

if (data.charAt(i) == ' ')

this means, if you find a space, this would mark the beginning of the next word. Also, the last word will not be counted so you should return Count+1 instead of Count.

There are several assumptions I made here:

  1. There will be exactly one space in between words.
  2. There will not be any leading or trailing spaces.

To consider multiple spaces between words, you would need to modify the code a little. Instead of checking if a character is space, check to see if a character is non-space and the previous character was either a space or no character for the case of first word. This would also handle leading and trailing spaces.


public class Main {

    public static void main(String[] args) {
        String data = "This is a Test";
        int wordCount = 1;
        int charCount = 0;
        for (int i = 0; i < data.length(); i++) {
            if (data.charAt(i) == ' ') {
                wordCount++;
            } else {
                charCount++;

            }
        }
        System.out.println("wordCount = " + wordCount);
        System.out.println("charCount = " + charCount);
    }
}


String ss =  "   leading spaces in string  ";
String[] sa = ss.trim().split("\\w+");
System.out.println(sa.length);

Note the use of trim to handle surrounding whitespace.


Use the below code for count the words in the line,

            int index = 0;
            int numWords =0;
            boolean prevwhitespace = true;
            String line = "bla bla bla bla";
            while(index < line.length())
            {
                char c = line.charAt(index++);
                boolean currwhitespace = Character.isWhitespace(c);
                if(prevwhitespace && !currwhitespace)
                {
                    numWords++;
                }
                prevwhitespace= currwhitespace;
            }
           System.out.println("no. of words in the line :: " +numWords);


My solution:

public static int getWordCount() {
  String data = "bla bla bla bla";
  String[] arr = data.split(" ");
  return arr.length;
}


String s = "Aljohani Abdallah";
int counter = 1;
for (int i = 0; i < s.length() - 1; i++) {
    if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ')
        counter++;
}
if (s == " ")
    counter = 0;
System.out.println(counter);

this code above here is count number of words in String so the first thing I have to know is length of the string and then we do if condition, if i was in index equals space at the same time must the letter after space not equal space the add 1 to counter

the end if the String was empty the counter should be zero.


String str = "  Hello there   my name     is   Bill    ";
str = str.trim();
int count = 0;
for(int i = 0; i<str.length(); i++) {
    if(str.charAt(i) == ' ' && str.charAt(i-1) != ' ') {
        count++;
    }
}

System.out.println(count+1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜