• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Tokenizer

 
Michael Taylor
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Taylor
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic