Trimming new line character from a string in java

2019-02-23 08:59发布

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?

2条回答
我命由我不由天
2楼-- · 2019-02-23 09:07

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();
查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-23 09:30

Strings are immutable. Change

token.trim();

to

token = token.trim();
查看更多
登录 后发表回答