aspose file tools*
The moose likes Beginning Java and the fly likes splitting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "splitting" Watch "splitting" New topic
Author

splitting

Joe Panully
Greenhorn

Joined: Oct 10, 2004
Posts: 22
If i have a string, and I want to split it on the white space and count the number of words in it how would i do this?

String sentance="Hello this is a sentance";
String[] output=sentance.split("\\s");

Than I don't really know what to do.
Barry Higgins
Ranch Hand

Joined: Jun 05, 2003
Posts: 89
Try the following

String sentance="Hello this is a sentance";
StringTokenizer st=new StringTokenizer(sentance);
int noOfTokens=st.countTokens();

Hope this helps,
Barry
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

If you split on the spaces, then each element of the resulting array will be a word. Therefore, the number of words is equal to the number of elements in the array, which you can access with the "length" variable.

int wordCount = output.length;


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
That code puts words into an array. The length field (well, it looks like a field) tells you how many words are in the array.

Be sure to test with some extraneous spaces and leading spaces, like

and see what happens. That may lead you to the JavaDoc on Pattern to see if you can match any number of spaces instead of just one. let us know how it goes!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: splitting