Home > Java > javaTutorial > How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?

How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?

DDD
Release: 2024-11-26 07:37:09
Original
293 people have browsed it

How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?

Java: Replacing Multiple Spaces with a Single Space and Eliminating Leading and Trailing Spaces

When working with strings in Java, it is often necessary to clean up whitespace. This includes removing leading and trailing spaces, as well as replacing multiple consecutive spaces with a single space.

Solution

To replace two or more spaces with a single space and delete leading and trailing spaces in Java, the following steps can be taken:

  1. Trim Leading and Trailing Spaces: Use the trim() method on the string to remove any spaces at the beginning or end.
  2. Replace Multiple Spaces with a Single Space: Use the replaceAll() method with the following regular expression:

    " +| "
    Copy after login

    This expression matches either two or more spaces (" ") or a single space (" ") and replaces it with a single space.

Using these steps, the following code can be used to convert a string with multiple spaces to a string with a single space:

String mytext = " hello     there   ";
String after = mytext.trim().replaceAll(" +| ", " ");
System.out.println(after); // Output: hello there
Copy after login

Additional Considerations

No trim() Regex:

While the trim() solution is more readable, it is also possible to achieve the desired result using a single replaceAll() method with a more complex regular expression:

String after = mytext.replaceAll("^ +| +$|( )+", "");
Copy after login

See Also:

  • [String.trim() documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim--)
  • [Regular Expressions Repetition](https://www.regular-expressions.info/Repetition)
  • [Regular Expressions Anchors](https://www.regular-expressions.info/Anchors)

The above is the detailed content of How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template