| Author |
String from JTextField
|
Gopu Akraju
Ranch Hand
Joined: Jan 13, 2008
Posts: 242
|
|
I am getting the user input through a JTextfield. 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
|
 |
Jelle Klap
Bartender
Joined: Mar 10, 2008
Posts: 1402
|
|
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.
|
 |
Gopu Akraju
Ranch Hand
Joined: Jan 13, 2008
Posts: 242
|
|
|
Yes thanks. I could remove all the white spaces using simple regex as
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
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.
|
 |
Gopu Akraju
Ranch Hand
Joined: Jan 13, 2008
Posts: 242
|
|
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 ]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19214
|
|
|
Use replaceAll then, using "\\s" to remove all whitespace, not only spaces.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Brian Cole
Author
Ranch Hand
Joined: Sep 20, 2005
Posts: 852
|
|
Originally posted by Gopu Akraju: I could remove all the white spaces using simple regex as
Others have pointed out some problems with this, namelyString.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 ]
|
bitguru blog
|
 |
Gopu Akraju
Ranch Hand
Joined: Jan 13, 2008
Posts: 242
|
|
|
Thanks and I learnt a lot.
|
 |
 |
|
|
subject: String from JTextField
|
|
|