Strip Leading and Trailing Spaces From Java String

To remove leading and trailing whitespace from a string in Java, you can use the trim method of the String class. This method returns a new string with the leading and trailing whitespace removed.

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

String s = "   Hello, world!   ";
s = s.trim();
System.out.println(s);  // Outputs "Hello, world!"

The trim method removes all leading and trailing whitespace characters from the string, including spaces, tabs, and newlines.

If you want to remove only leading or trailing spaces, you can use the stripStart and stripEnd methods of the String class, respectively. These methods were introduced in Java 11 and provide more efficient alternatives to trim for removing leading or trailing spaces only.

Here is an example of how you can use the stripStart and stripEnd methods:

String s = "   Hello, world!   ";
s = s.stripStart();
System.out.println(s);  // Outputs "Hello, world!   "
s = s.stripEnd();
System.out.println(s);  // Outputs "Hello, world!"

I hope this helps! Let me know if you have any other questions.