Home >Java >javaTutorial >How to Remove Leading and Trailing Spaces from Java Strings?

How to Remove Leading and Trailing Spaces from Java Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 14:35:48320browse

How to Remove Leading and Trailing Spaces from Java Strings?

Removing Leading and Trailing Spaces from Java Strings

In Java, spaces preceding and following a string are often undesirable. To effortlessly eliminate these unwanted spaces, Java offers a convenient solution: the trim() method.

To utilize the trim() method, simply invoke it on the desired string as follows:

<code class="java">String trimmedString = originalString.trim();</code>

This operation effectively removes any leading or trailing whitespace characters from the original string.

For instance, consider the following example:

<code class="java">String myString = "  keep this  ";
String trimmedString = myString.trim();
System.out.println("Trimmed String: " + trimmedString);</code>

When this code is executed, it will print:

Trimmed String: keep this

As demonstrated, the trim() method has successfully eliminated the spaces from both the beginning and end of the string, leaving only the desired content.

Note that unlike the replace() method, trim() does not alter the content of the original string. Instead, it creates a new string with the spaces removed.

The above is the detailed content of How to Remove Leading and Trailing Spaces from Java Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn