Sunday, October 8, 2023

2 Ways to remove whitespaces from String in Java? Example Tutorial

You can remove blanks for whitespaces from a Java String by using the trim() method of java.lang.String class of JDK API. Unlike SQL Server which have LTRIM() and RTRIM() methods to remove whitespace from String, Java doesn't have ltrim() and rtrim() methods to trim white spaces from left and right, instead it just have a trim() method which removes all spaces from String including space at the beginning and at the end. Since String is Immutable in Java, it's worth noting that this method return a new String if original String contains space either at beginning or end, otherwise it will return the same String back. 

It's also worth noting that trim() method doesn't trim whitespace between words, it just shaves off white spaces from start and end of String. In this tutorial, I will show you how to first check if String contains whitespace or not and then how thow remove all spaces or blanks from a given String in Java.


How to check if string contains whitespace in Java?

You can use the indexOf(), contains() and lastIndexOf() method to check if a String contains whitespace or not. If it contains blank then contains() will return true and both indexOf() and lastIndexOf() will return starting index of the white space and not -1

Here is the sample example you can use to do this check using each of these methods:

1. Check whitespace in String using indexOf()

public class WhitespaceCheck {
    public static void main(String[] args) {
        String str = "Hello World";

        // Using indexOf()
        if (str.indexOf(' ') != -1) {
            System.out.println("String contains whitespace using indexOf()");
        } else {
            System.out.println("String does not contain whitespace using indexOf()");
        }
    }
}

2. How to check whitespace using contains() method

public class WhitespaceCheck {
    public static void main(String[] args) {
        String str = "Hello World";

        // Using contains()
        if (str.contains(" ")) {
            System.out.println("String contains whitespace using contains()");
        } else {
            System.out.println("String does not contain whitespace using contains()");
        }
    }
}

3. How to check String contains whitespace using lastIndexOf()

public class WhitespaceCheck {
    public static void main(String[] args) {
        String str = "Hello World";

        // Using lastIndexOf()
        if (str.lastIndexOf(' ') != -1) {
            System.out.println("String contains whitespace using lastIndexOf()");
        } else {
            System.out.println("String does not contain whitespace using lastIndexOf()");
        }
    }
}

These examples assume that you want to check for the presence of any whitespace character (including space, tab, etc.). If you specifically want to check for space character only, you can replace the whitespace character with ' ' in the examples.

2 Ways to Remove Whitespace from String in Java

Now that you have understood how to check if String contains whitespace or not, it's time to actually remove whitespace from String.  I will show you three scenarios which I have faced in day to day coding for removing whitespace from beginning, end or removing multiple whitespaces from String in Java. We will use both trim() method and regular expression to to remove white space from String in Java. 

1. Removing space from beginning of the String

To remove spaces from the beginning of a string in Java, you can use the trim() method along with substring() or regular expressions. Here are examples using both approaches:

public class RemoveLeadingSpaces {
    public static void main(String[] args) {
        String str = "    Hello World";

        // Using trim() and substring()
        String trimmedStr = str.trim();
        System.out.println("Original String: " + str);
        System.out.println("String after removing leading spaces: " + trimmedStr);
    }
}

This approach works by first using trim() to remove leading and trailing spaces and then obtaining the substring starting from the first non-space character.

Using Regular Expressions

public class RemoveLeadingSpaces {
    public static void main(String[] args) {
        String str = "    Hello World";

        // Using regular expressions
        String trimmedStr = str.replaceFirst("^\\s+", "");
        System.out.println("Original String: " + str);
        System.out.println("String after removing leading spaces: " + trimmedStr);
    }
}

Here, the regular expression "^\\s+" matches one or more whitespace characters at the beginning of the string (^ denotes the start of the string, and \s represents whitespace).

You can choose the approach that fits your needs and coding style. Both will remove leading spaces from the given string.

2. Remove multiple spaces from string in java

To remove multiple spaces from a string in Java, you can use regular expressions along with the replaceAll() method. Here's an example:

public class RemoveMultipleSpaces {
    public static void main(String[] args) {
        String str = "This   is    a   string    with   multiple   spaces";

        // Using regular expressions and replaceAll()
        String trimmedStr = str.replaceAll("\\s+", " ");
        
        System.out.println("Original String: " + str);
        System.out.println("String after removing multiple spaces: " + trimmedStr);
    }
}

In this example, the regular expression \\s+ matches one or more whitespace characters (\s denotes whitespace, and + denotes one or more occurrences). The replaceAll("\\s+", " ") method replaces sequences of one or more spaces with a single space.

This will result in a string with consecutive spaces reduced to a single space:

Original String: This   is    a   string    with   multiple   spaces
String after removing multiple spaces: This is a string with multiple spaces

You can also use this code and adjust the code according to your specific requirements.

2 Ways to remove whitespaces from String in Java? Example Tutorial


That's all about how to remove white spaces or blank from String in Java. Unlike SQL Sever and Sybase, Java doesn't provide ltrim() and rtrim() method instead it just provide trim() method to remove both leading and trailing whitespaces in Java String.

Other Java String articles You may like:

  • Why was the String class made final in Java? (answer)
  • how to make Immutable class in Java? (example)
  • How substring method of String works in Java? (answer)
  • Why char[] is better than String for storing a password in Java? (answer)
  • 10 Things Every Java Programmer should know about String? (answer)
  • How String in switch case works in Java 7? (answer)
  • How to format String in Java? (answer)
  • How to join String in Java 8 (example)
  • 15 Java Stream and Functional Programming interview questions (list)
  • How to check if String is null or empty in Java? (solution)

Thanks for reading this article so far. If you have any question or feedback then please drop a note note, happy to answer any query you may have. 
   

No comments :

Post a Comment