Home » Android » Android – java – count words

Android – java – count words

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&Answers:

You want to split on arbitrary strings of whitespace, rather than just space characters. So, use .split("\\s+") instead of .split(" ").

Answer:

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.

Answer:

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.