aspose file tools*
The moose likes Beginning Java and the fly likes My String won't trim Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "My String won Watch "My String won New topic
Author

My String won't trim

Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
I have a GUI with a JPassword field named pswrd.
When I read the entered password I save it in a String
named password and trim to get out leading and trailing
empty spaces (user pressed the space bar).

but when I print the password (using a JOptionPane)

to check that the empty spaces are gone, they never are.
Why, and what can I do about it?
Thanks!
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
This is a standard mistake when working with Strings. Strings are immutable, meaning they do not change. The syntax "password.trim();" does nothing to the original String, it simply returns a NEW String with the spaces trimmed off. The following modification will work:
password = password.trim();
Hope this helps.
Joe
Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello,
Hope this too clarify the answer, according to the API specification of the String class,
trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Important thing to note here is that, it returns a String.
Better check the API if you get similar problems.
Cheers...........


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Amin Rais
Greenhorn

Joined: Aug 28, 2002
Posts: 20
String in Java is immutable. So you can't change it instead get the new trimmed String.
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
Oh geez! I really should have seen that...
Thanks ya'll, Elouise
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: My String won't trim
 
Similar Threads
String and StringBuffer roundup
How to validate text fields ?
How to remove spaces
WHAT THE $%#^%# IS HAPPENING HERE?
How to trim spaces between characters of string using javascript