7

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

I used .trim()

What else could be a reason for this?

1
  • 4
    You'll have to show us your code, because as stated, it's not possible. Commented May 30, 2010 at 16:26

3 Answers 3

28

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());
Sign up to request clarification or add additional context in comments.

1 Comment

5 minute response time?!?! Come on guys, we can do better than that... ;)
12

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.

2 Comments

+1 It's a good diagnostic tool even if it wasn't needed this time.
Didn't even have the same problem is OP but this really helped figure out that the string was using ANSI escape codes. +1
-2

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")

1 Comment

length() does not return the length of the backing array, and it should be able to be trimmed. See my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.