java

How to remove multiple spaces from a string in Java

In this tutorial, we are going to see how to remove spaces from a String in Java.

In the below example, we’ll use the replaceAll() method of the String class to remove all white space (including tabs) from a string. This is one of the easiest ways to remove spaces from a string in Java. The replaceAll() method takes two parameters. One is the string to be replaced and the other is the new string. We pass the string "\\s+" to be replaced by an empty string "". This method removes spaces at the end, at the beginning, and between words.
 

How to remove multiple spaces from a string in Java
public class Main {

    public static void main(String[] args) {
        String str = "S    tack How        To";
        System.out.println("Word with spaces: " + str);

        str = str.replaceAll("\\s", "");
        System.out.println("Word without spaces: " + str);
    }
}

Output:

Word with spaces: S    tack How        To
Word without spaces: StackHowTo
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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