Home > Java > javaTutorial > How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?

How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?

Susan Sarandon
Release: 2024-11-30 09:55:11
Original
546 people have browsed it

How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?

Java: Replacing Multiple Spaces with Single Space and Trimming Leading and Trailing Spaces

To address the task of reducing multiple spaces to a single space and eliminating leading and trailing spaces, we have several Java solutions.

Solution 1: Using trim() and replaceAll()

This solution utilizes the trim() method to remove the leading and trailing spaces, followed by replaceAll() to combine multiple spaces into a single space:

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

Solution 2: Regex-only

While less readable, it's feasible to resolve the problem with a single replaceAll() utilizing a complex regular expression:

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

Solution Details

  • Solution 1: trim() removes all leading and trailing whitespace, while replaceAll() replaces consecutive spaces with a single space.
  • Solution 2: The regex achieves the same result in a single step. It matches and replaces sequences of spaces at the beginning, end, or middle of the string with either an empty string (to remove extra spaces) or a single captured space (to keep single spaces intact).

Additional Resources

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

The above is the detailed content of How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template