Wednesday 22 November 2017

java - string trim function is not working





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



Answer




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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...