Home >Java >javaTutorial >How to Efficiently Remove Multiple Spaces from a Java String?

How to Efficiently Remove Multiple Spaces from a Java String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 15:24:12970browse

How to Efficiently Remove Multiple Spaces from a Java String?

How to Remove Multiple Spaces from a String in Java

In Java, a common task is to clean up strings by removing extra spaces and leading or trailing whitespaces. Here's how to achieve this:

To replace multiple consecutive spaces with a single space, use the replaceAll method with a regular expression:

String mytext = " hello     there   ";
mytext = mytext.replaceAll(" +", " ");

This regex matches one or more consecutive spaces ( ) and replaces them with a single space.

To remove leading and trailing spaces while also collapsing multiple spaces, use trim and replaceAll in combination:

String after = before.trim().replaceAll(" +", " ");

trim removes spaces at the beginning and end of the string, and replaceAll replaces multiple spaces within the string with a single space.

For more control over matching and replacing whitespace, consider using anchors and capturing groups in the provided regex example:

String[] tests = {
    "  x  ",
    "  1   2   3  ",
    "",
    "   ",
};
for (String test : tests) {
    System.out.format("[%s]%n",
        test.replaceAll("^ +| +$|( )+", "")
    );
}

This regex is more complex but allows for precise matching and replacement of whitespace.

The above is the detailed content of How to Efficiently Remove Multiple Spaces from a Java String?. 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