Trimming new line character from a string in java

纵然是瞬间 提交于 2019-12-01 22:05:12

问题


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?


回答1:


Since String is immutable

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

token = token.trim();



回答2:


Strings are immutable. Change

token.trim();

to

token = token.trim();


来源:https://stackoverflow.com/questions/18899013/trimming-new-line-character-from-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!