Android - java - word count

I have edittext, and I want to count the words in it. Something is wrong when there are new lines in the editor.

I tried this:

String[] WC = et_note.getText().toString().split(" ");
Log.i("wordcount", "wc: " + WC.length);

This is text → wc: 4

it

and

text → wc: 4

it

plain

text → wc: 4

Any ideas?

+6
source share
4 answers

You want to separate spaces into arbitrary lines, not just space characters. So use .split("\\s+")instead .split(" ").

+9
source

I suggest using BreakIterator . In my experience, this is the best way to cover non-standard languages ​​like Japanese, where there are no spaces that separate words.

An example of word counting is here .

+3
source

/ :

String words = str.trim();
if (words.isEmpty())
return 0;
return words.split("\\s+").length; // separate string around spaces  

You can also use \\ W here instead of \\ s if you could have something other than a space separating the words.

0
source

@Rajesh Panchal

This is the best, I think. Thank you

0
source

All Articles