问题
I learned string.trim()
removes leading and trailing spaces. But in my case its not working i am trying below code but output is with leading and trailing space. But my expectation is text without leading and trailing space. Here is my code.
String s = " Hello Rais ";
s += " Welcome to my World ";
s.trim( );
System.out.println(s);
Please help me
回答1:
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
回答2:
In Java Strings are immutable
. So s.trim()
does not modify the original string but returns a new string.
String trimmed = s.trim();
回答3:
just add s=s.trim( );
because trim returns a new string.
回答4:
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();
回答5:
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.
回答6:
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.
来源:https://stackoverflow.com/questions/14919019/string-trim-function-is-not-working