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
How to Correctly Decode Unicode Parameters Passed to a Servlet
How Often Should Connection, Statement and Resultset Be Closed in Jdbc
How to Resize Jlabel Imageicon
Java.Lang.Stackoverflowerror While Using a Regex to Parse Big Strings
Getting the Difference Between Two Sets
How to Pause and Resume a Thread in Java from Another Thread
How to Convert a 1D Array to 2D Array
(Unknown Source) in Exception Stack Trace
Keeping the Correct Style on Text Retrieval
Java Best Practice for Date Manipulation/Storage for Geographically Diverse Users
How to Set Working Directory with Processbuilder
Java Swing; Two Classes, Where to Put If Statements and New Actionlisteners
Reverse a Given Sentence in Java
How to Do a Fractional Power on Bigdecimal in Java