Java: Remove Spaces from String

Removing spaces from a string is a common task in Java. This guide will cover different ways to remove spaces, including using the replace and replaceAll methods, the StringBuilder class, and the Stream API (Java 8 and later).

Table of Contents

  1. Introduction
  2. Using replace Method
  3. Using replaceAll Method
  4. Using StringBuilder Class
  5. Using Stream API
  6. Conclusion

Introduction

In Java, strings are sequences of characters. Removing spaces from a string involves eliminating all whitespace characters. This can be done using various methods, each suited to different scenarios.

Using replace Method

The replace method of the String class can be used to remove all spaces from a string by replacing them with an empty string.

Example

public class RemoveSpacesExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        String result = str.replace(" ", "");

        System.out.println("Original String: \"" + str + "\"");
        System.out.println("String without spaces: \"" + result + "\"");
    }
}

Explanation

  • The replace method is called on the string str with the space character as the target and an empty string as the replacement.
  • All spaces in the string are replaced with an empty string.

Output:

Original String: "Hello World!"
String without spaces: "HelloWorld!"

Using replaceAll Method

The replaceAll method of the String class can be used to remove all spaces from a string using a regular expression.

Example

public class RemoveSpacesExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        String result = str.replaceAll("\\s", "");

        System.out.println("Original String: \"" + str + "\"");
        System.out.println("String without spaces: \"" + result + "\"");
    }
}

Explanation

  • The replaceAll method is called on the string str with the regular expression \\s (which matches any whitespace character) as the target and an empty string as the replacement.
  • All whitespace characters in the string are replaced with an empty string.

Output:

Original String: "Hello World!"
String without spaces: "HelloWorld!"

Using StringBuilder Class

The StringBuilder class can be used to remove spaces from a string by manually appending non-space characters to a StringBuilder object.

Example

public class RemoveSpacesExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        String result = removeSpaces(str);

        System.out.println("Original String: \"" + str + "\"");
        System.out.println("String without spaces: \"" + result + "\"");
    }

    public static String removeSpaces(String str) {
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Explanation

  • A StringBuilder object is created.
  • A loop iterates through each character of the string.
  • If the character is not a whitespace character, it is appended to the StringBuilder.
  • The final string without spaces is returned.

Output:

Original String: "Hello World!"
String without spaces: "HelloWorld!"

Using Stream API

The Stream API (introduced in Java 8) provides a modern and concise way to remove spaces from a string.

Example

import java.util.stream.Collectors;

public class RemoveSpacesExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        String result = removeSpaces(str);

        System.out.println("Original String: \"" + str + "\"");
        System.out.println("String without spaces: \"" + result + "\"");
    }

    public static String removeSpaces(String str) {
        return str.chars()
                  .filter(c -> !Character.isWhitespace(c))
                  .mapToObj(c -> String.valueOf((char) c))
                  .collect(Collectors.joining());
    }
}

Explanation

  • A stream is created from the characters of the string using str.chars().
  • The filter method is used to keep only non-whitespace characters.
  • The mapToObj method converts the characters back to strings.
  • The collect method joins the characters back into a single string without spaces.

Output:

Original String: "Hello World!"
String without spaces: "HelloWorld!"

Conclusion

Removing spaces from a string in Java can be accomplished using various methods, each with its own advantages. The replace and replaceAll methods provide simple and direct ways to remove spaces. The StringBuilder class offers a manual and flexible approach. The Stream API provides a modern and functional programming approach, making the code more readable and expressive. Depending on your specific use case and preferences, you can choose the method that best fits your needs.

Comments