从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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:06:39  来源:igfitidea点击:

Trimming new line character from a string in java

javastringnewlinetrim

提问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)?

如何从字符串的开头和结尾删除换行符(Java)?

says otherwise.

否则说。

What am I missing?

我错过了什么?

采纳答案by Sotirios Delimanolis

Since Stringis immutable

因为String是不可变的

token.trim();

doesn't change the underlying value, it returns a new Stringwithout 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();