Thursday 8 December 2016

java - string trim function is not working

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...