Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

splitting

 
Joe Panully
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic