10

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?

erdomester
  • 11,789
  • 32
  • 132
  • 234

4 Answers4

15

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

Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
4

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.

  • 2
    I created a simple String extension function in Kotlin which uses BreakIterator. Checkout my [Gist](https://gist.github.com/ElegyD/65ad990d505ee20239ef5a3c16eec951) – ElegyD Jul 06 '18 at 10:21
3

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.

Rajesh Panchal
  • 1,140
  • 3
  • 20
  • 39
-1

Late answer but i do it like this

String a = text.replaceAll("\s+","+");

String b = a.replaceAll("[^+]", "");

textview1.setText(String.valueOf((long)(b.length() + 1)));

  • 1
    A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it. – Tyler2P Jan 29 '22 at 09:03