• (cs)

    One of these days, a programming language will include some sort of replace() function.

  • (cs)

    thats still not c++ ;-;

  • Keith Hackney (unregistered)

    fist!

  • Keith Hackney (unregistered)

    dup!

    Everyone knows the best way to remove spaces is to take a screenshot of the string, print it out, physically cut the spaces out using a scalpel, reassemble the rest of the string, place it on a wooden table, take a photo of it and then scan in the photo.

    The Real WTF is that they didn't use PHP and XML.

    CAPTCHA = comb-over

  • (cs) in reply to Keith Hackney
    Keith Hackney:
    The Real WTF is that they didn't use PHP and XML.

    Have they tried javascript?

    captcha: Why use anything when you have javascript..

  • Anonymous (unregistered) in reply to akatherder

    you mean like in C# or Java

  • Anonymous (unregistered) in reply to akatherder

    you mean like in C# or Java

  • Jimmy (unregistered) in reply to Keith Hackney
    Keith Hackney:
    dup!

    Everyone knows the best way to remove spaces is to take a screenshot of the string, print it out, physically cut the spaces out using a scalpel, reassemble the rest of the string, place it on a wooden table, take a photo of it and then scan in the photo.

    The Real WTF is that they didn't use PHP and XML.

    CAPTCHA = comb-over

    No, the Real WTF is that they didn't use J#.

  • (cs)

    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

  • Tepid Perl User (unregistered) in reply to akatherder
    akatherder:
    One of these days, a programming language will include some sort of replace() function.

    Well,

     s/ //g
    

    is good enough for all those sed and perl users out there...

    Captha : dubya. Dubya Bush?

  • Magus (unregistered) in reply to sir_flexalot
    sir_flexalot:
    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

    That's assuming your test that one string equals another string with space removed works correctly. You could make an error, such as testing that the two strings are equal ignoring spaces.

  • Ted (unregistered)

    my version:

    char* RemoveSpaces( char *str ) { if ( NULL == str ) return NULL;

    char *to = str;
    char *from = str;
    
    do{
        if( *str != ' ' ) *to++ = *str;
    while( *str++ != '\0 );
    
    return str;
    

    }

  • (cs)

    Thank god this is very easy and straightforward in Java:

    public String removeSpaces(String paula) {
      String willy = "";
      StringTokenizer george = new StringTokenizer(paula, " ");
      while(george.hasMoreTokens()) {
        willy = new String(willy.toString() + george.nextToken().toString();
      }
      return paula.replaceAll(" ", "")
    }
    
  • C.M (unregistered)

    I was called in to fix an old Excel add-in written in VBA. It's the worst code I've ever seen...

    Example: Two functions used everywhere in the code to change change " " to "_" or the other way around.

    Function Change_toBlankforText(txt As String) As String
    Dim n As Integer
    Dim retur As String
        retur = ""
        For n = 1 To Len(txt)
            If Mid(txt, n, 1) <> "_" Then
                retur = retur & Mid(txt, n, 1)
            Else
                retur = retur & " "
            End If
        Next n
        Change_toBlankforText = retur
    End Function
    
    Function ChangeBlankto_forText(txt As String) As String
    Dim n As Integer
    Dim retur As String
        retur = ""
        For n = 1 To Len(txt)
            If Mid(txt, n, 1) <> " " Then
                retur = retur & Mid(txt, n, 1)
            Else
                retur = retur & "_"
            End If
        Next n
        ChangeBlankto_forText = retur
    End Function
    

    I chose to replace it with this instead:

    Replace(txt, " ", "_")

    There's enough WTF's in this add-in to fill a whole month of submissions. /C.M

  • Sandpit (unregistered)

    Use a real language such as VB6:

    Replace(myString, " ", "")

    (Captcha= ewww)

  • SomeCoder (unregistered)

    The STL C++ way:

    string str = "I have spaces to remove"; string newStr = ""; newStr.resize(str.length()); remove_copy_if(str.begin(), str.end(), newStr.begin(), bind2nd(equal_to<char>(), ' '));

    // newStr == "Ihavespacestoremove"

    There's probably some other ways using the STL too.

  • Poltras (unregistered)

    Here's another unit-tested version (which works, although might not should... or whatever)... Please note the C standard lib notations.

    // String Remove Spaces.  Isnt that obvious?
    void strrms( char *p )
       char *s=(char*)calloc(strlen(p)*sizeof(char),1);
       char *c=strtok(p," ");
       while(c) strcat(s,c), c=strtok(0," ");
       strcpy(p,s);
    }

    BTW, I think there is a better (read shorter and more obscure) way to make the while loop, but I don't have much time.

    captcha: darwin. Give some of those to the ppl who write here without knowing what they talk about.

  • ForcedSterilizationsForAll (unregistered) in reply to sir_flexalot
    sir_flexalot:
    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

    That only works if you then compare the two strings character by character, making sure to take the case into account.

  • TekdOut (unregistered) in reply to sir_flexalot

    with the a little help from a quantum computer...this solutuion would take no time at all

  • (cs) in reply to sir_flexalot
    sir_flexalot:
    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

    How do you then generate thestringwithoutspaces for the comparision in the termination condition? There must be a neat recursive solution here...

    sub strip_spaces { my $s = shift;

    my $r; while ($r = generate_random_string() ne strip_spaces($s)) {}; return $r; }

  • Sgt. Preston (unregistered) in reply to Sandpit
    Sandpit:
    Use a real language such as VB6:

    Replace(myString, " ", ""))

    Or use another real language such as VB.NET (in which our WTF is written):

    myString = myString.Replace(" ","")
  • Nomikos (unregistered) in reply to SomeCoder

    I think I like the Haskell way better:

    removeSpaces = filter (/= ' ')
  • Sgt. Preston (unregistered)

    Casting my mind all the way back to February 22nd has me feeling all nostalgic. We should have Classics Week at least once a month.

  • Monkey (unregistered) in reply to Poltras

    Not shorter but more obscure?

    char *removespaces(char *str)
    {
       char *p_from = str, *p_to = str;
       while(*p_to) *p_to++ = *(p_from += (*p_from == ' ') ? 1: 0), p_from++;
       return str;
    }
    
  • CynicalTyler (unregistered)

    I still prefer feeding my spaces to demonic forces to get rid of them...

    http://worsethanfailure.com/Comments/Removing_Spaces,_the_Easy_Way.aspx?pg=2#121986

  • AJ (unregistered)

    The source for this version is longer than both the WTF "reference" and Monkey's version (and unlike Ted's version it actually compiles), but g++ generates fewer machine instructions for it:

    char* rmSpaces(char* str) {
        if (str) {
            char* to = str;
            char* from = str;
            char ch;
    
            do {
                ch = *from++;
                if (' ' != ch)
                    *to++ = ch;
            } while ('\0' != ch);
        }
        return str;
    }
  • Peter Lawrey (unregistered)

    Or in Java

    myString = myString.replaceAll(" +", "");
    // to remove white space.
    myString = myString.replaceAll("\\s+", "");
    
  • D (unregistered) in reply to Monkey
    Monkey:
    Not shorter but more obscure?
    char *removespaces(char *str)
    {
       char *p_from = str, *p_to = str;
       while(*p_to) *p_to++ = *(p_from += (*p_from == ' ') ? 1: 0), p_from++;
       return str;
    }
    
    Would that even work? What does the following return?
    removespaces("this  has  multiple     spaces    in   a row");
  • (cs)

    How about designing functions that don't restrict you to removing or replacing just one character?

    #include <stdio.h>
    
    static char *strremove(char *, char);
    static char *strreplace(char *, char, char);
    
    int
    main(int argc, char *argv[])
    {
        char rem[] = " I have spaces to remove ";
        char rep[] = " I have spaces to replace ";
    
        printf("'%s'\n", strremove(rem, ' '));
        printf("'%s'\n", strreplace(rep, ' ', '_'));
    
        return 0;
    }
    
    char *
    strremove(char *str, char c)
    {
        char *to, *from;
    
        if (str) {
            for (to = from = str; *from; ++from)
                if (*from != c)
                    *to++ = *from;
            *to = '\0';
        }
    
        return str;
    }
    
    char *
    strreplace(char *str, char o, char n)
    {
        char *to, *from;
    
        if (str) {
            for (to = from = str; *from; ++from)
                if (*from != o)
                    *to++ = *from;
                else
                    *to++ = n;
            *to = '\0';
        }
    
        return str;
    }
  • Reaver (unregistered) in reply to Skurry
    Skurry:
    Thank god this is very easy and straightforward in Java:
    public String removeSpaces(String paula) {
      String willy = "";
      StringTokenizer george = new StringTokenizer(paula, " ");
      while(george.hasMoreTokens()) {
        willy = new String(willy.toString() + george.nextToken().toString();
      }
      return paula.replaceAll(" ", "")
    }
    

    Typical.

    While Willy and George are dicking around with their 'tokens', Paula is getting the job done on her own.

    Bet the guys try and take the credit as well...

    ;->

    Cheers, Reaver

  • (cs)

    void removespaces(char *target, char *src) { if(*src && *src++ != ' ') *target++ = src[-1]; if(*src) removespaces(target,src); }

    elegantly bizarre.

    Addendum (2007-05-11 12:50): oops. forgot "else*target=0". also, the "*src &&" in the first condition is not strictly necessary

    void removespaces(chartarget,charsrc){if(*src++!=' ')*target++=src[-1];if(src)removespaces(target,src);elsetarget=0;}

  • FlyboyFred (unregistered) in reply to SomeCoder
    SomeCoder:
    The STL C++ way:

    string str = "I have spaces to remove"; string newStr = ""; newStr.resize(str.length()); remove_copy_if(str.begin(), str.end(), newStr.begin(), bind2nd(equal_to<char>(), ' '));

    // newStr == "Ihavespacestoremove"

    There's probably some other ways using the STL too.

    Much easier:

    string str = "I have spaces to remove"; str.erase(remove(str.begin(), str.end(), ' '), str.end());

    Or for char arrays:

    char* removeSpaces(char* buf) { int len = strlen(buf); std::remove(buf, buf+len+1, ' '); return buf; }

  • (cs)
    void vacuum(std::string &s) {
            for (int x = 0; x < s.length(); x++)
                    if (isspace(s[x]))
                            s.erase(x, 1); 
    }
  • Robert (unregistered)

    I am so glad I know PHP and can do this so much better in it. If only they would come up with some sort of str_replace() function though... Oh well.

    <?php
    function rs($s)
    {
        if ($s == '') return;
        if ($s == ' ') return '';
        $r = ' ';
        $sl = strlen($s);
        $st = '';
        for ($i = 0; $i < $sl; ++$i)
        {
            if ($s[$i] == $r)
            {
                $s[$i] = '';
            }
            
            $st .= $s[$i];
        }
        
        return $st;
    }
    ?>

    CAPTCHA: howdy RESPONSE: Fine, and you?

  • (cs)

    I don't even know what the hell the Try/Catch is supposed to be doing

    Well, in most languages string operations like MID/Substring cause the allocation of a new string, hence memory allocation, which can fail raising an exception... :P

    Seriously, this is one of the things most quickly forgotten by C++ MFC developers that do know how CString objects really work.

  • (cs) in reply to Kiasyn
    Kiasyn:
    thats still not c++ ;-;
    Not sure if you are serious or not because of the strange kinda-sorta-smiley, but it really is C++...

    This line:

    for ( char* from = str ; '\0' != *from ; ++from )

    -Will not compile in plain C.

  • (cs) in reply to jtwine

    Assuming it's followed by a statement or a block, why not?

    Or are you still using the c89 standard? That's so... 1989.

    incidentally, "'\0' !=" is a no-op.

    for(char *from=str;*from;++from) { ... }

    perfectly valid c99.

  • Claudiu Saftoiu (unregistered)

    Python way is a one-liner! Probably for other scripting languages too:

    string = "hey i want to remove spaces? kk" removed = "".join(c for c in string if c != ' ') removed 'heyiwanttoremovespaces?kk'

    or alternatively:

    filter(lambda x: x!=' ', string) 'heyiwanttoremovespaces?kk'

    or a faster but even stranger looking way

    filter(' '.ne, string) 'heyiwanttoremovespaces?kk'

  • duuuuuude (unregistered)

    Everyone say it with me now...

    "Regular Expressions Are Your Friends!"

  • (cs)

    Dammit, in both occurrences of this article, I posted my vacuum method, and not once has anyone commented how clever my name for it was. :(

  • (cs) in reply to sir_flexalot
    sir_flexalot:
    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

    Wort sorting algorithm ever: Generate all possible permuations of the input, and return the one that is sorted.

    OR, keep randomly generating permutations of the input, and return when the one you hit on, happens to be sorted.

  • Aurélien (unregistered) in reply to Claudiu Saftoiu

    Or even simpler: removed = string.replace(" ", "")

  • Claudiu Saftoiu (unregistered) in reply to Aurélien

    Lol. Yeah, I guess that would be the fastest, simplest way. Silly me.

  • -M- (unregistered) in reply to Claudiu Saftoiu

    Or...you could do it like real python.. string = 'hey i want to remove spaces? kk' string = string.replace(' ','')

  • Claudiu Saftoiu (unregistered) in reply to -M-

    in my goal of finding a quick one-line way to do it, i forgot str had a replace function. I promise, my python code is better than that usually!

  • kupal (unregistered)

    the real wtf is that he should've used regular expression to find the space then have an character array that stores the non-space characters then converting it to a string when finished parsing.

    captcha: putanginamo

  • SuperBlah (unregistered) in reply to Poltras

    Don't try to use this in a multithreaded application if you're using strtok. Also, 'more obscure' does not equal 'better'.

  • Joseph Newton (unregistered) in reply to java.lang.Chris;
    java.lang.Chris;:
    How about designing functions that don't restrict you to removing or replacing just one character?
    #include <stdio.h>
    
    static char *strremove(char *, char);
    static char *strreplace(char *, char, char);
    
    int
    main(int argc, char *argv[])
    {
        char rem[] = " I have spaces to remove ";
        char rep[] = " I have spaces to replace ";
    
        printf("'%s'\n", strremove(rem, ' '));
        printf("'%s'\n", strreplace(rep, ' ', '_'));
    
        return 0;
    }
    
    char *
    strremove(char *str, char c)
    {
        char *to, *from;
    
        if (str) {
            for (to = from = str; *from; ++from)
                if (*from != c)
                    *to++ = *from;
            *to = '\0';
        }
    
        return str;
    }
    
    char *
    strreplace(char *str, char o, char n)
    {
        char *to, *from;
    
        if (str) {
            for (to = from = str; *from; ++from)
                if (*from != o)
                    *to++ = *from;
                else
                    *to++ = n;
            *to = '\0';
        }
    
        return str;
    }

    Aside from the use of literals o, n, and c where old_char new_char, and gone_char would do better, this is the clearest solution I've seen on this thread. I'd note also that C does allow the use of parameter names in function declarations, and that using meaningful names would make those declarations self-commenting.

  • ehird (unregistered)
    char *rmchar(char *buf, char *src, char rm)
    {
    	char *i, *j;
    	for (i = str, j = buf; *i; j++) if (*i != rm) *j++ = *i;
    	return buf;
    }

    QED.

  • Matthew (unregistered) in reply to sir_flexalot
    sir_flexalot:
    I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

    Hey, it's O(1)!

    Or would that be O(rand(1))?

    -matthew

Leave a comment on “Classics Week: Removing Spaces, the Easy Way”

Log In or post as a guest

Replying to comment #:

« Return to Article