Difference between revisions of "Remove blanks from a string"

From CodeCodex

(Tcl)
(OCaml)
Line 17: Line 17:
 
Use regular expressions to replace sequences of one or more spaces with nothing:
 
Use regular expressions to replace sequences of one or more spaces with nothing:
  
  # let remove_blanks = Str.global_replace (Str.regexp "[ ]+") "";;
+
  # let remove_blanks = Str.global_replace (Str.regexp " +") "";;
 
  val remove_blanks : string -> string = <fun>
 
  val remove_blanks : string -> string = <fun>
  

Revision as of 02:30, 11 February 2007

Related content:

Implementations

Java

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;
}

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