erdomester
erdomester

Reputation: 11829

Android - java - count words

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?

Upvotes: 10

Views: 6593

Answers (4)

ErdiKara
ErdiKara

Reputation: 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)));

Upvotes: -1

Viktor Mitev
Viktor Mitev

Reputation: 61

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.

Upvotes: 5

Rajesh Panchal
Rajesh Panchal

Reputation: 1170

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.

Upvotes: 3

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

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

Upvotes: 15

Related Questions