Remove blanks from a string

From CodeCodex

Revision as of 23:20, 8 October 2007 by Tanktop (Talk | contribs)

Related content:

Implementations

Java

public static String deleteBlanks(String s) {
    StringBuilder result = new StringBuilder();
    int length = s.length();
    for (int i=0; i<length; i++  ) {
        char ch = s.charAt(i);
        if (ch != ' ') {
            result.append(ch);
        }
    }
    return result.toString();
}

OCaml

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!"

Python

a = "hello world! how are you?"
b = a.replace(" ", "")

Perl

$a = "hello world! how are you?";
$a =~ s/[ ]//g;

Tcl

proc remove_blank_using_list s {join [split $s " "] ""}
proc remove_blank_using_regsub s {regsub -all " " $s ""}
remove_blank_using_list "hello world! how are you?"
remove_blank_using_regsub "hello world! how are you?"

Visual Basic

sString = Replace(sString, " ", "")

e.g. function to remove spaces from a string:

Public Function RemoveSpaces(sString as String) As String
    RemoveSpaces = Replace(sString, " ", "")
End Function

Or to replace double spaces with single spaces:

Public Function RemoveDoubleSpaces(sString as String) As String
    RemoveSpaces = Replace(sString, "  ", " ")
End Function