GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes String Tokenizer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Tokenizer" Watch "String Tokenizer" New topic
Author

String Tokenizer

Michael Taylor
Greenhorn

Joined: Jun 19, 2002
Posts: 15
I need to figure out how to eliminate leading spaces, trailing spaces, and extra spaces between words entered as a String from the user. I would also like to return the numbers of words contained in the text. Can anyone help?
Thanks,
Michael
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
The String class has a trim method that will trim leading and trailing white space. The StringTokenizer class has a countTokens() method that will determine the number of tokens remaining. The Character class has a isSpaceChar and a isWhitespace method that will tell you if a character is a space character. See the Java docs for further information.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Michael Taylor
Greenhorn

Joined: Jun 19, 2002
Posts: 15
I can't seem to get the trim() to work. Here is my entire exercise. I may be heading in the wrong direction.
Given a string(a text entered as a long string) entered by a user from the command line.
1. Write a program that eliminates leading spaces, trailing spaces, as well as extra spaces between words. (we assume one space seperates two words).
2. Your program also returns the number of words contained in the text.

I am thinking now that I should use an array to perform this exercise. Any ideas.
Thanks,
Michael.
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865

Looks like the StringTokenizer does all of the work for you.
When you run the program, make sure that you put the String in quotes. Otherwise, Java will put each word in a separate element of the String array parameter for main.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String Tokenizer