Results 1 to 3 of 3
- 04-29-2012, 07:46 AM #1
Senior Member
- Join Date
- Apr 2012
- Posts
- 211
- Rep Power
- 0
String trim() member function not working
I ran across an issue with the trim function not working in my main code, so I made a little test program and got the same results. Why isn't the trim function removing the first white space (byte = 32).
Java Code:myString = " defined(OPENSSL_SYS_VMS)"; myString.trim(); byte[] bytesFromString = myString.getBytes("UTF-8"); for (byte byteFromString: bytesFromString) { System.out.println(byteFromString); }
32
100
101
102
105
110
101
100
40
79
80
69
78
83
83
76
95
83
89
83
95
86
77
83
41
- 04-29-2012, 08:25 AM #2
Senior Member
- Join Date
- Apr 2012
- Posts
- 211
- Rep Power
- 0
Re: String trim() member function not working
I found the problem.
trim() doesn't change the original string. I should have assigned the result of myString.trim() to a new string.
- 04-29-2012, 08:28 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Re: String trim() member function not working
First of all, the trim() method works. Just saying, but it does. "Unexpected output from trim()" might better have expressed the problem.
And led us to examine the trim() API docs to see what the devil we should expect trim() to do. "Returns a copy of the string, with leading and trailing whitespace omitted".
The important bit is "a copy of". In your code you obtain the byte array from myString - the original string - not from the copy returned by trim().
[Edit] too slow! :( I'm glad you've you got it figured out. This is behaviour consistent with the other String methods, and methods of so-called (and much favoured) immutable classes.Last edited by pbrockway2; 04-29-2012 at 08:31 AM.
Similar Threads
-
The function append() not working.
By gautham0209 in forum AWT / SwingReplies: 4Last Post: 11-20-2011, 08:32 AM -
Trim() doesn't trim()
By trl in forum New To JavaReplies: 4Last Post: 08-29-2011, 08:55 AM -
Trim for null string
By laosu in forum New To JavaReplies: 3Last Post: 02-08-2011, 07:56 AM -
String.trim() method help.....
By arson09 in forum New To JavaReplies: 6Last Post: 04-23-2010, 02:19 AM -
String trim
By Java Tip in forum Java TipReplies: 0Last Post: 01-21-2008, 05:35 PM
Bookmarks