string trim function is not working [closed]

≯℡__Kan透↙ 提交于 2019-11-28 14:08:06

You need to re-assign the result of trim back to s:

s = s.trim();

Remember, Strings in Java are immutable, so almost all the String class methods will create and return a new string, rather than modifying the string in place.


Although this is off-topic, but (as I said there almost), it's worth knowing that, exception to this rule is when creating a substring of same length, or any time a method returns the string with the same value, which will be optimized and will not create a new string, but simply return this.

String s = "Rohit";
String s2 = s.substring(0, s.length());

System.out.println(s == s2); // will print true

In Java Strings are immutable. So s.trim() does not modify the original string but returns a new string.

String trimmed  = s.trim();

just add s=s.trim( ); because trim returns a new string.

Well..string is immutable object. so whenever you do trim(), it creates a brand new String object, which need to have a reference to access it. So do assign a reference to this trimmed String object as follows.

s = s.trim();

or

trimmedS = s.trim();

Understand that String in Java is immutable. Which means any operation on the String class does not change the internal string itself, but returns a new String object.

So you really need to do

s = s.trim()

which assigns the reference s to a new String object that has its trailing and leading spaces removed.

trim function returns a copy of the original string by trimming the white spaces so you need to store the newly returned string like s = s.trim()

From the javadocs of String#trim()

trim

public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!