Explain Codes LogoExplain Codes Logo

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

java
string-manipulation
performance-optimization
regex
Nikita BarsukovbyNikita Barsukov·Feb 26, 2025
TLDR

Here you go, a one-liner to replace multiple spaces with a single one and remove leading and trailing spaces in Java:

String result = input.replaceAll("\\s+", " ").trim();

In this code, \\s+ matches successive spaces, replaceAll squeezes them into a single space, and trim() masterfully shoos away trailing and leading spaces. It's like a magic wand, turning your pumpkin string into a golden-carriage result.

Mastering space manipulation in Java

Space management and performance matters

Time is the enemy of performant code. Long strings can drain precious time, and when you're battling against the clock, invert the operations:

String result = input.trim().replaceAll(" +", " ");

Now trim() is getting the first dibs, chopping off leading and trailing spaces. This allows replaceAll() to focus on de-duping the rest. Like taking care of your bulk order backlog before dealing with today's orders.

Libraries to the rescue

In Java's humble standard library, we might not meet every challenge. Summon a trusted friend for your mission, Apache Commons Lang, save the day with StringUtils:

String result = StringUtils.normalizeSpace(input);

This method trims, and also normalizes whitespace—replacing consecutive whitespace characters with a single space, like a pro groundskeeper turning a ragged lawn into a golf course.

Deep-diving with regex

Ever gazed at the \\s+ and wondered about its mystic powers? Here's a quick spellbook for casting regex magic in Java: \\ is the required escape sequence, \\s targets any whitespace character, and + signifies one or more occurrences.

Different spells suit different wizards. If you want to pinpoint two or more spaces specifically, here's an alternative:

String result = input.replaceAll("\\s{2,}", " ").trim();

Ensuring pristine strings always

Keep your strings neat and clean by adhering to these practices:

  • Test with examples: Check with different strings and edge cases, whether it's War and Peace or a blank note.
  • Understand your tools: Go look under the hood of this beautiful trim() car and understand what makes this regex engine roar!
  • Check your work: Always test your code. Remember: what can go wrong, will go wrong. It's just Murphy's Law!

The tightrope: readability vs. performance

This age-old tug-of-war often requires a trade-off. Readability may lose against performance and vice versa. For critical systems where speed is king, performance optimization is key. For anything else, learn to lean towards the side of clarity for sustainability.