Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the exact number of words in a string that has empty spaces between words?

Tags:

java

Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.

I made a function:

public static int wordCount(String s){

  int counter = 0;

  for(int i=0; i<=s.length()-1; i++) {

    if(Character.isLetter(s.charAt(i))){

      counter++;

      for(i<=s.length()-1; i++){

        if(s.charAt(i)==' '){

          counter++;
        }
      }                
    }
  }

  return counter;
}

But i know this has 1 limitation that it will also count the number of spaces after all the words in the string have finished nad it will also count 2 blank spaces as possibly being 2 words :( Is there a predefined function for word count? or can this code be corrected?

like image 254
Iam APseudo-Intellectual Avatar asked Jan 19 '12 10:01

Iam APseudo-Intellectual


1 Answers

If you want to ignore leading, trailing and duplicate spaces you can use

String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
like image 196
Peter Lawrey Avatar answered Oct 23 '22 18:10

Peter Lawrey