tags:

views:

172

answers:

3

I have the string "22" and I'm getting 3 as length;

I used .trim()

What else could be a reason for this?

+6  A: 

Try this:

System.out.println(java.util.Arrays.toString(theString.toCharArray()));

This dumps the char[] version of the String, so we can perhaps see if it contains anything funny.

polygenelubricants
+1 It's a good diagnostic tool even if it wasn't needed this time.
Mark Peters
+17  A: 

You should be giving us code that demonstrates the problem, but my guess is you did something like this:

String str = "22 ";
str.trim();
System.out.println(str.length());

But str.trim() doesn't change str (as Strings are immutable). Instead it returns a new String trimmed. So you need something like this:

String str = "22 ";
str = str.trim();
System.out.println(str.length());
Mark Peters
yup thats it, wow you guys are quick O_o
Jan
5 minute response time?!?! Come on guys, we can do better than that... ;)
CrazyJugglerDrummer
A: 

since i found a reason while formulating the question, im gonna answer myself..

If the string was created by .substring or split, the whole string is saved plus the position and length of the substring.

this apparently cant be trimmed (was " 22")

Jan
`length()` does not return the length of the backing array, and it should be able to be trimmed. See my answer.
Mark Peters
wrong, it can, see answer above
Jan