从java中的字符串中修剪换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18899013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trimming new line character from a string in java
提问by Vicky
The output of below program:
以下程序的输出:
public class TestClass {
public static void main(final String[] args){
String token = "null\n";
token.trim();
System.out.println("*");
System.out.println(token);
System.out.println("*");
}
}
is:
是:
*
null
*
However
然而
How to remove newlines from beginning and end of a string (Java)?
says otherwise.
否则说。
What am I missing?
我错过了什么?
采纳答案by Sotirios Delimanolis
Since String
is immutable
因为String
是不可变的
token.trim();
doesn't change the underlying value, it returns a new String
without the leading and ending whitespace characters. You need to replace your reference
不会改变底层值,它返回一个String
没有前导和结束空格字符的新值。您需要更换您的参考
token = token.trim();
回答by NPE
Strings are immutable. Change
字符串是不可变的。改变
token.trim();
to
到
token = token.trim();