Return to Snippet

Revision: 1671
at November 6, 2006 10:11 by limonn


Initial Code
public static String deleteBlanks(String s) {
    String result = "";
    for (int i=0; i<s.length(); i++) {
        if (!s.substring(i, i+1).equals(" ")) {
            result = result + s.substring(i, i+1);
        }
    }
    return result;
}


--------------------------------------------------------------

Use regular expressions to replace sequences of one or more spaces with nothing:

# let remove_blanks = Str.global_replace (Str.regexp "[ ]+") "";;
val remove_blanks : string -> string = <fun>

For example:

# remove_blanks "He llo w orl d!";;
- : string = "Helloworld!"

Another solution, using the Micmatch library and the POSIX definition of a blank, i.e. space or tab:

# let remove_blanks = REPLACE blank -> "";;   
val remove_blanks : ?pos:int -> string -> string = <fun>
# remove_blanks "He llo w orl d!";; 
- : string = "Helloworld!"

Or directly:

# (REPLACE blank+ -> "") "He llo w orl d!";;
- : string = "Helloworld!"

For replacing spaces only, use the following variant:

# (REPLACE " "+ -> "") "He llo w orl d!";;                        
- : string = "Helloworld!"

Initial URL
http://www.codecodex.com/wiki/index.php?title=Remove_blanks_from_a_string

Initial Description

                                

Initial Title
triming blank spaces

Initial Tags

                                

Initial Language
Java