remove white spaces from a string

4. How to remove white spaces from a string in Java : best ways

Way 1: Remove white spaces from a string: Using regular expression.

To remove white spaces from a string in Java, you can use the replaceAll() method from the String class along with a regular expression. Here’s an example:

String str = "  Hello,  World!  ";
String trimmedStr = str.replaceAll("\\s+", "");

System.out.println(trimmedStr);

Output:

Hello,World!

In the code above, the regular expression \\s+ matches one or more white space characters. The replaceAll() the method replaces all occurrences of the matched pattern with an empty string, effectively removing all white spaces from the original string.

Note that this code removes all white spaces, including spaces, tabs, and newlines. If you only want to remove leading and trailing white spaces, you can use the trim() method:

String str = "  Hello,  World!  ";
String trimmedStr = str.trim();

System.out.println(trimmedStr);

output:

Hello,  World!

The trim() method removes leading and trailing white spaces from the string but preserves any white spaces within the string.

Way 2: Remove white spaces from a string: Without using inbuilt methods.

If you don’t want to use the built-in methods for removing white spaces, you can implement a custom solution using loops and conditional statements. Here’s an example:

public class RemoveWhiteSpaces {
    public static void main(String[] args) {
        String str = "  Hello,  World!  ";
        String trimmedStr = removeWhiteSpaces(str);

        System.out.println(trimmedStr);
    }

    public static String removeWhiteSpaces(String str) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                sb.append(str.charAt(i));
            }
        }

        return sb.toString();
    }
}

Output:

Hello,World!

In this example, the removeWhiteSpaces() the method takes a string as input and iterates over each character. It checks if the character is a white space using the Character.isWhitespace() method. If the character is not white space, it appends it to an StringBuilder object. Finally, it returns the string representation of the StringBuilder using the toString() method.

Note that this code removes all white spaces, including spaces, tabs, and newlines. If you only want to remove leading and trailing white spaces, you can modify the removeWhiteSpaces() method as follows:

public static String removeWhiteSpaces(String str) {
    int start = 0;
    int end = str.length() - 1;

    while (start <= end && Character.isWhitespace(str.charAt(start))) {
        start++;
    }

    while (end >= start && Character.isWhitespace(str.charAt(end))) {
        end--;
    }

    return str.substring(start, end + 1);
}

This code uses two pointers (start and end) to find the indices of the first and last non-white space characters. It then returns the substring between these indices, effectively removing leading and trailing white spaces.

Way 3: Remove white spaces from a string: using Pattern and Matcher.

Here’s an alternative way to remove white spaces from a string using Pattern and Matcher classes without using the replaceAll() method:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    public static void main(String[] args) {
        String str = "  Hello,  World!  ";
        String trimmedStr = removeWhiteSpaces(str);

        System.out.println(trimmedStr);
    }

    public static String removeWhiteSpaces(String str) {
        Pattern pattern = Pattern.compile("\\s");
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            matcher.appendReplacement(sb, "");
        }
        matcher.appendTail(sb);

        return sb.toString();
    }
}

Output:

Hello,World!

In this approach, we create a Pattern object with the regular expression \\s, which matches a single white space character. Then, we create a Matcher object using the pattern and the input string.

Next, we use a StringBuffer (or StringBuilder) to build the resulting string. The matcher.find() method is used in a loop to find each occurrence of the white space character in the string. Within the loop, the matcher.appendReplacement() method is called to replace the matched white space with an empty string. The replacements are appended to the StringBuffer.

Finally, after the loop, the matcher.appendTail() method is called to append the remaining part of the original string that comes after the last matched white space. The toString() method is then used to retrieve the final trimmed string from the StringBuffer and return it as the result.

Remove leading and trailing spaces from a string

To remove leading and trailing spaces from a string in Java, you can use the trim() method, which is available in the String class. Here’s an example:

String str = "   Hello, World!   ";
String trimmedStr = str.trim();
System.out.println(trimmedStr);

Output:

Hello, World!

In the example above, the trim() method is called on the str string. It removes any leading and trailing whitespace characters from the string and returns a new string with the spaces removed. The resulting trimmed string is then printed to the console.

You can run above all code here just copy and paste.

Other String Related Posts:

Ram Chadar

Hello! I'm Ram Chadar, a passionate software developer and freelancer based in Pune. Welcome to my blog, where I share my experiences, insights, and knowledge in the world of software development, different technologies, freelancing, and more.

View all posts by Ram Chadar →

Leave a Reply

Your email address will not be published. Required fields are marked *