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
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>
Joined: Jun 19, 2002
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.
Joined: Jul 02, 2002
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.