Replace multiple spaces in a string with single space in java - Java @ Desk

Thursday, May 16, 2013

Replace multiple spaces in a string with single space in java

Explanation :
Use replace all method of string and check for more than one occurence of space using regular expression "\\s+" and replace with " " {blank space}

public class ReplaceMultiSpacesWithSingleSpace {
    public static void main(String args[]) {
        String string = "My    name    is    kumar";
        System.out.println("Original String : "+string);
        System.out.println("Resulting String : "+string.replaceAll("\\s+", " "));
    }
}

Output :
Original String : My    name    is    kumar
Resulting String : My name is kumar






No comments:

Post a Comment