I have an edittext and I want to count the words in it. There is something wrong when there are new lines in the edittext.
I tried this:
String[] WC = et_note.getText().toString().split(" ");
Log.i("wordcount", "wc: " + WC.length);
This is a text -> wc: 4
This is
a
text -> wc: 4
This is
a simple
text -> wc: 4
Any ideas?
You can count words in Java String by using the split() method of String. A word is nothing but a non-space character in String, which is separated by one or multiple spaces. By using a regular expression to find spaces and split on them will give you an array of all words in a given String.
You want to split on arbitrary strings of whitespace, rather than just space characters. So, use .split("\\s+")
instead of .split(" ")
.
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
String words = str.trim();
if (words.isEmpty())
return 0;
return words.split("\\s+").length; // separate string around spaces
You could also use \\W here instead of \\s, if you could have something other than space separating words.
I'd suggest to use BreakIterator. According to my experience this is the best way to cover not standard languages like Japanese where there aren't spaces that separates words.
Example of word counting here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With