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
Release: 2024-10-23 14:35:48
Original
324 people have browsed it

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>
Copy after login

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>
Copy after login

When this code is executed, it will print:

Trimmed String: keep this
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template