简体   繁体   English

Java:使用trim()后得到不正确的string.length()

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

I have the string "22" and I'm getting 3 as length; 我有字符串"22" ,长度为3;

I used .trim() 我用.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). 但是str.trim()不会更改str (因为字符串是不可变的)。 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. 这将转储char[]版本的String ,因此我们也许可以查看它是否包含任何有趣的东西。

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. 如果字符串是由.substring或split创建的,则将保存整个字符串以及子字符串的位置和长度。

this apparently cant be trimmed (was " 22") 显然无法修剪(是“ 22”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM