Even though I call trim function to remove the blank spaces, I am getting this problem. When the user types like "test " (i.e name followed by space bar), the space created by space bar does not get removed from the string. How do I remove it and make it as "test". Do I have to check character by character? Thanks. Regards
Remember strings are immutable. The trim() method returns a new String object from which leading and trailing whitespaces have been removed. In your code exmaple you're ignoring this return value and using the original String object - which still includes whitespaces.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Joined: Jan 13, 2008
Yes thanks. I could remove all the white spaces using simple regex as
Originally posted by Gopu Akraju: Yes thanks. I could remove all the white spaces using simple regex as
Not a good idea. That will remove included spaces and change "Gopu Akraju" to "GopuAkraju".
What you actually want is String name = nameText.getText().trim(); as Jelle Klap has already hinted.
Joined: Jan 13, 2008
YEs that is true. I tried both ways and works perfect for me. I have to remove all the white spaces in the string, not only in the starting and at the end. Hence regex, gives me a compact string. [ May 08, 2008: Message edited by: Gopu Akraju ]
Originally posted by Gopu Akraju: I could remove all the white spaces using simple regex as
Others have pointed out some problems with this, namely
String.replace() isn't a regex method. Use String.replaceAll() for regex replacement.
" " will replace only spaces, not other whitespace.
You probably don't want to get rid of whitespace between words.
But those things aside, you still have the original problem. name.replace(" ", ""); does not modify name but instantiates a new String object, so you would want something like name = name.replace(" ", "");
Probably easiest is to just do name = name.trim() as it doesn't have the above problems. [ May 08, 2008: Message edited by: Brian Cole ]