Difference between revisions of "Remove blanks from a string"

From CodeCodex

m (Reverted edit of Cj4I2v, changed back to last version by Ldo)
Line 6: Line 6:
 
     StringBuilder result = new StringBuilder();
 
     StringBuilder result = new StringBuilder();
 
     int length = s.length();
 
     int length = s.length();
     for (int i=0; i<length; i++) {
+
     for (int i=0; i<length; i ) {
 
         char ch = s.charAt(i);
 
         char ch = s.charAt(i);
 
         if (ch != ' ') {
 
         if (ch != ' ') {
Line 19: Line 19:
 
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>
  
Line 34: Line 34:
  
 
Or directly:
 
Or directly:
  # (REPLACE blank+ -> "") "He llo w orl d!";;
+
  # (REPLACE blank -> "") "He llo w orl d!";;
 
  - : string = "Helloworld!"
 
  - : string = "Helloworld!"
  
 
For replacing spaces only, use the following variant:
 
For replacing spaces only, use the following variant:
  # (REPLACE " "+ -> "") "He llo w orl d!";;                         
+
  # (REPLACE " " -> "") "He llo w orl d!";;                         
 
  - : string = "Helloworld!"
 
  - : string = "Helloworld!"
  

Revision as of 22:29, 1 September 2007

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