Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 278
erdomester Avatar asked May 01 '12 19:05

erdomester


People also ask

How do you count words in Java?

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.


3 Answers

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

like image 180
Gareth McCaughan Avatar answered Oct 19 '22 03:10

Gareth McCaughan


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.

like image 37
Rajesh Panchal Avatar answered Oct 19 '22 03:10

Rajesh Panchal


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.

like image 4
Viktor Mitev Avatar answered Oct 19 '22 03:10

Viktor Mitev