String 的trim 方法内部会调用substring方法,你去阅读源码可以看到substring 的最终会是new String (value,begin,sublen)。
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
s.trim() 和s 是两个地址,你的打印方法中还是 s.lenth();
正确的应该是:
String s = " ab ";
s = s.trim();
System.out.println("长度:" + s.length());
public static void main(String[] args) {
String str = " ad ";
str = str.trim();
System.out.println(str.length());
}