I can’t see any difference! You might find it looks better if I add code tags, because the forum software does not support double whitespace. And you should not use StringTokenizer at all, as you will find it you read its documentation. And it is not a method.
You need to get away from the String class. Remember String is not intended for changes.
I shall let you do some lateral thinking before telling you anything, but at least three ways to do it came to mind in a minute. They all have similarities.
Joined: Oct 13, 2005
I see Ernest has beaten me to it with the code tags. Thank you.
I don't want to simply write the code for you, but...
Imagine that you are a tiny bug, and you can only look at one character of the string at a time. You crawl from left to right over the characters, and yell out the ones that aren't spaces.
Now, how could you implement that in code? You need to visit each character. You can read a character using one of String's member functions (look at the javadocs for java.lang.String) and you can use a loop (what kind of loop?) to repeat for each character.
Rd Dari wrote:Ya Campbell,
You are right that String is immutable in java.
then it is possible to remove extra white space from this string with the other way.
Yes, String is immutable, so you can't change that String. But you can do what trim() and replaceAll(), etc. do. You can create a new String based on the original, but leaving out the characters you don't want. Consider that, and the previous suggestion to pretend you're a bug walking along the String, and look closely and carefully at the documentation for the java.lang.String class to find what it provides that might help you.
Joined: Oct 13, 2005
Rd Dari wrote: . . . then it is possible to remove extra white space from this string
Of course it is.
with the other way.
What do you mean other way? You mean other ways, surely.
I note that replaceAll() was not mentioned as a method you aren't allowed to use. That's the one that I would use, if it's allowed, to solve this problem. However (a) it's quite possible the interviewer doesn't want you to use that, either; (b) you need to know a bit about regular expressions to use replaceAll() here; and (c) it's definitely good practice to do this without replaceAll(), using the hints the others have been giving. It's probably useful to figure out how to do it several different ways, as Campbell noted.