String .trim() method in java

‮.www‬lautturi.com
String .trim() method in java

The trim method in Java is a method of the java.lang.String class that removes leading and trailing white space characters from a string. It returns a new string with the white space removed, and the original string remains unchanged.

Here's an example of how you can use the trim method:

String s = "   Hello, World!   ";
String sTrimmed = s.trim();
System.out.println(sTrimmed);  // prints "Hello, World!"

Note that the trim method only removes white space characters from the beginning and end of the string. It does not remove white space characters within the string. If you want to remove all white space characters from a string, you can use the replaceAll method with a regular expression that matches white space characters:

String s = "   Hello, World!   ";
String sWithoutSpaces = s.replaceAll("\\s", "");
System.out.println(sWithoutSpaces);  // prints "Hello,World!"
Created Time:2017-10-17 08:56:51  Author:lautturi