Java
String Manipulation
Programming
Spaces Removal
Coding Tutorial

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

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

In Java, managing white spaces in strings is a frequent requirement, especially when processing or formatting textual data received from various inputs like user input, data files, or network sources. One specific task that often needs to be addressed is replacing sequences of two or more spaces with a single space and removing any leading or trailing spaces from a string. This operation is crucial for data normalization, which can be critical for subsequent operations like comparisons, searches, or display formatting.

Using String Methods

Java provides several built-in methods in the String class to manipulate strings, including trimming and replacing characters.

Trimming Leading and Trailing Spaces

To remove leading and trailing spaces, Java's String class includes the trim() method which is quite straightforward to use:

java
String original = "   Hello World!   ";
String trimmed = original.trim();
System.out.println(trimmed); // Output: "Hello World!"

The trim() method removes whitespace from the beginning and the end of the string. It’s important to note that this method only affects spaces and does not impact intermediary spaces.

Replacing Multiple Spaces with a Single Space

Replacing multiple consecutive spaces with a single one requires a different approach. This can be achieved using the replaceAll() method of the String class, which takes a regular expression as its first argument:

java
String withSpaces = "Hello    World!   Have  a   Nice Day!";
String normalized = withSpaces.replaceAll("\\s{2,}", " ").trim();
System.out.println(normalized); // Output: "Hello World! Have a Nice Day!"

Here, \\s{2,} is a regular expression that matches any sequence of two or more whitespace characters. The replaceAll() method replaces each sequence found with a single space. The trim() method is then used to remove any leading and trailing spaces.

Using Regular Expressions

Regular expressions (regex) are a powerful tool for string manipulation and pattern matching. In the Java example above, \\s{2,} describes the regex pattern:

  • \\s - represents a single whitespace character, including spaces, tabs, new line characters, etc.
  • {2,} - quantifier specifying a match of at least two occurrences of the preceding character class (\\s).

This approach is not only useful for spaces but can also be generalized to handle other types of whitespace or repetitive character sequences.

Performance Considerations

While the replaceAll() method is very powerful due to its flexibility with regex, it might not always be the most efficient solution for very large strings or scenarios where performance is critical. Using a StringBuilder to manually iterate through the string and construct a new one based on custom logic might be faster but requires more code.

Practical Applications

Normalizing spaces in strings is common in numerous applications, including:

  • User Input Sanitization: Ensuring that multiple spaces entered by users don't affect program logic or database queries.
  • Data Parsing: Often data coming from external sources like CSV files contains extra spaces that need to be managed.
  • Text Processing: In natural language processing, consistent spacing can be crucial for tasks like tokenization or parsing.

Summary Table

MethodUsageDescription
trim()original.trim()Removes leading and trailing spaces.
replaceAll()text.replaceAll("\\s{2,}", " ")Replaces sequences of two or more spaces with a single space. Uses regex for pattern matching.

Conclusion

Managing and manipulating strings efficiently in Java is a must-have skill for developers. Knowing how to handle whitespace effectively aids in creating robust and error-free applications. Using String methods in conjunction with regex provides a toolbox suitable for most situations where string normalization regarding spaces is required. Each approach has its place depending on the specific needs of the project, including code clarity, maintainability, and performance.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms