Remove blanks from a string
From CodeCodex
| Image:Lightbulb.png Related content: |
| <DPL>
category=String shownamespace=false </DPL> |
Contents |
[edit] Implementations
[edit] Haskell
filter (/=' ')
[edit] Java
public static String deleteBlanks(String s) {
return s.replaceAll("\\s", "");
}
[edit] C
if buff's content is: "he llo wo r ld! how ar e y ou?" then the content of buff_02 will be: "helloworld!howareyou?"
#include "string.h"
int i=0, j=0;
int len = (int)strlen(buf);
while (i != len) {
if (buff[i] != ' ')
buff[j++] = buff[i];
i++;
}
buff[j]=0;
or using char pointer you may use the following variant:
char *i=(char*)buf, *j=(char*)buf;
do {
if (*i != ' ')
*(j++) = *i;
} while (*(i++));
[edit] D
auto a = "hello world! how are you?";
auto b = a.replace(" ", "");
[edit] 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!"
[edit] PHP
$a = "hello world! how are you?";
$b = str_replace(" ", "", $a);
[edit] Python
a = "hello world! how are you?"
b = a.replace(" ", "")
[edit] Perl
$a = "hello world! how are you?"; $a =~ s/ +//g;
[edit] Seed7
a := "hello world! how are you?"; b := replace(a, " ", "");
[edit] 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?"
[edit] 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
[edit] WinBatch
; Remove blanks from a string strString = "Hello, World! I am here, where are you? " strString = StrReplace (strString, " ", "") ; "Hello,World!Iamhere,whereareyou?" ; This code example was written by Detlev Dalitz.
[edit] Zsh
a="Hello, World! How are you?"
b=${a// /}
Categories: String | C | Java | Objective Caml | PHP | Python | Perl | Seed7 | Tcl | Visual Basic | WinBatch | Zsh

