Count Words in a String Method

Count words in a string method?

public static int countWords(String s){

int wordCount = 0;

boolean word = false;
int endOfLine = s.length() - 1;

for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}

Count the number of all words in a string

You can use strsplit and sapply functions

sapply(strsplit(str1, " "), length)

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

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;

Counting words in string

Use square brackets, not parentheses:

str[i] === " "

Or charAt:

str.charAt(i) === " "

You could also do it with .split():

return str.split(' ').length;

Use pattern matcher to count words in a string

I don't think that you can solve this problem with regex.

This is a solution by using a Set:

    String str = " I have two cars   in my garage and my dad has one   car in his garage ";
System.out.println(str);

String low = str.trim().toLowerCase();

String[] words = low.split("\\s+");

Set<String> setOfWords = new HashSet<String>(Arrays.asList(words));

low = " " + str.toLowerCase() + " ";
low = low.replaceAll("\\s", " ");

for (String s : setOfWords) {
String without = low.replaceAll(" " + s + " ", "");
int counter = (low.length() - without.length()) / (s.length() + 2);
if (counter > 1)
System.out.println(s + " repeated " + counter + " times.");
}

it will print

 I have two cars   in my garage and my dad has one   car in his garage 
in repeated 2 times.
garage repeated 2 times.
my repeated 2 times.


Related Topics



Leave a reply



Submit