This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Well the input string comes from a TextArea. I'm using getText to get the text from the TextArea. I'm not actually typing the newlines or tabs into the String myself, java places them there from the TextArea. For example...
Here's the code:
I type the following text into inputTextField: Brandi Love was here!
and get the following output: BrandiLove washere!
It has removed the spaces but not the newline. Very frustrating. [ February 27, 2007: Message edited by: Brandi Love ]
Go through your text, divide it into a char array, then use a for loop to go through the individual characters. Don't print them out straight, but print them using a %x tag (or %d if you like decimal numbers).Get an ASCII table and look up all the numbers for the characters, and see whether there are any \n or \f or \r. Do this before or after.
You might be more successful if you write a regular expression (see this part of the Java Tutorial, etc) which includes whitespace and line terminators, and use it as a delimiter with the String.split() method, then print the individual tokens in order.
Hope this helps. CR [ February 28, 2007: Message edited by: Campbell Ritchie ]
If you want to simply get rid of all white space, you could try
inputString = inputString.replaceAll("\\s", "");
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Sep 19, 2003
That worked wonderfully Ilja. Thanks for your help, everyone!
It's also not true - a tab is not the same as a combination of spaces, even if it ends up having an equivalent effect. A tab is a distinct character in Unicode, and a regex which replaces only spaces will have no effect on a tab. On the other hand, using \s (or "\\s") for whitespace is much more flexible - this is a predefined character class which recognizes multiple forms of whitespace, including standard spaces, and tabs.
On the off chance that the standard definition of whitespace does not apply, you can also construct a custom character class for the occasion. For example, a literal reading of the first post above implies that we should replace newlines, tabs, and spaces - but not returns, form feeds or vertical tabs. (The last two are virtually unused nowadays, but just in case you're dealing with data from 1970 or so...) To replace only those specific characters, you could use something like this:
In most cases using \s is both more concise and more accurate - but if it's not exactly what you need, you can always modify it.