开发者

Java: getting incorrect string.length() after using trim()

I have the string "22" a开发者_运维技巧nd I'm getting 3 as length;

I used .trim()

What else could be a reason for this?


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());


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜