• MR (unregistered)

    The C# 3.0 way of doing it (string.Replace is for wimps)

    static string NoSpaces(string s)
    {
        return new string(s.Where(c => c != ' ').ToArray());
    }
    
    static string NoSpaces2(string s)
    {
        return new string(
            (from c in s
             where c != ' '
             select c).ToArray());
    }
    
  • Andy (unregistered) in reply to Claudiu Saftoiu

    Nice Idea to use filter(). But I prefer: string.replace(" ", "")

  • TK (unregistered)

    It's just typical newbie code. I'm sure i've written something like than back in the days.

  • kevin (unregistered)

    php

    $str = str_replace(' ','',$str);

  • (cs) in reply to Joseph Newton
    Joseph Newton:
    java.lang.Chris;:
    How about designing functions that don't restrict you to removing or replacing just one character?
    static char *strremove(char *, char);
    static char *strreplace(char *, char, char);
    
    char *
    strremove(char *str, char c)
    {
        ...
    }
    
    char *
    strreplace(char *str, char o, char n)
    {
        ...
    }

    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.

    I agree. Although I use the same parameter names in the library which contains the originals of these functions, the header file has Doxygen comments that clearly describe each parameters purpose.

  • (cs) in reply to ehird
    ehird:
    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.

    That's seriously broken. Firstly, "str" is not declared, I assume you meant "src". You never increment i, but always increment j - twice if you do the assignment. Even if you change the for statement to increment i rather than j, you don't null terminate the destination array. A fixed version would be:

    char *
    rmchar(char *dst, const char *src, char rm)
    {
        const char *i;
        char *j;
        for (i = src, j = dst; *i; i++)
            if (*i != rm)
                *j++ = *i;
        *j = '\0';
        return dst;
    }

    I suggest you clear your desk and remember to hand in your pass to security as you leave the building.

  • Sin Tax (unregistered) in reply to Tepid Perl User
    Tepid Perl User:
    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?

    TMTOWTDI:

    $str =~ y/ //d;

    (And this just might be a little more efficient, depending on how Perl optimises the single space RE.

    Captcha: kungfu. (How'bout perl-fu? Or bar-fu?)

    -Sin Tax

  • Kcis Mi (unregistered)
    /* erm, da-it-da-erm, dah blah erm oort oort oort */
    char* rm0x20s(char *O) 
    {
    return(O)?{char *o,*Oo;for(*o=*Oo=O;*Oo;(0!=*Oo)?*o++=*Oo++:*Oo++);*o=0;O;}:O;
    } 
    
  • Kcis Mi (unregistered)

    /* erm, da-it-da-erm, dah blah erm oort oort oort / char rm0x20s(char *O) { return(O)?{char *o,*Oo;for(*o=*Oo=O;*Oo;(0x20!=*Oo)?*o++=*Oo++:*Oo++);*o=0;O;}:O; }

  • andy (unregistered)

    Nice memory leak on that benchmark C++ code.

  • tlesher (unregistered) in reply to DWalker59
    DWalker59:
    Wort sorting algorithm ever: Generate all possible permuations of the input, and return the one that is sorted.

    Nah. Could be worse: generate all possible permutations of the input into a balanced binary tree, then do a depth-first traversal, removing any that are not sorted. If the resulting tree is empty, return "-1" (error); if it contains more than one node, return "-2" (another error); otherwise, return the root node.

    (The subtle defect comes at no extra charge.)

  • Cruncher (unregistered)

    I find it perpetually amusing that Perl is declared to be a write-only language by people who profess any other language under the sun, and then proceed to demonstrate the sheer simplicity and beauty of Perl's power by giving examples in their favorite language; the examples being this inscrutable, non-intelligable gibberish of odd syntax. There is beauty in simplicity. There is tremendous power in simplicity. There is great speed (programmer speed) in simplicity.

    $string = "something with spacess I dont care how many are there"; @array = m/(\S+)/g; # capture all non-white space (e.g. tokenize) $string2 = $string; $string2 =~ s/\s+/ /g; # replace all multiple white spaces with a single space $string =~ s/\s+//g; # remove all white space from string

    Adding some printfs to this, and running it in Perl printf "string: %s\n",$string; printf "string2: %s\n",$string2;

    perl x.pl string: somethingwithspacessIdontcarehowmanyarethere string2: something with spacess I dont care how many are there

    You can have power and simplicity. Or you can choose more complex languages which require some of the oddest syntax, strangest function or chained method calls to do something as simple and elegant as was done above. Or you can chose to use languages marketed by a computer maker which look like little more than solutions looking for problems, and are square pegs to every round hole that exist or will be invented. PT Barnum's quote comes to mind, about fooling some of the people ...

    I suspect the python could be made more intelligable. Ruby syntax isn't bad, and you might be able to do something similar to the Perl. But in all cases, imagine how much wasted time and effort one could go through by not using a language that is designed to make programmers more efficient.

    The amount of wasted effort, re-inventing wheels is startling. The amount of criticism heaped upon tools that make the user of tools more productive, is mind boggling. Its even funnier when considering that the "write-only" aspects, i.e. the regular expressions of Perl, which give it quite a bit of awesome power, are being included now in a variety of languages. Imitation is the sincerest form of flattery.

    If you want to use a powerful language that won't get in your way with brain-dead methods and weird syntactical gymnastics, look at Perl and related. If you dont mind languages that do get in your way, force you to do things in a particular manner, which is not conducive to solving your problems, prevents you from using powerful tools, look at some of the other languages.

  • int19h (unregistered)

    Still no proper STL version given, so here's one:

    void remove_spaces(std::string& s) { s.resize(std::remove(s.begin(), s.end(), ' ') - s.begin()); }

    This is in-place, O(s.size())

  • Nall-ohki (unregistered) in reply to int19h

    void removeSpaces(char* c1) { if ( ! c1 || ! *c1 ) return; char c2 = c1;

    do
    {
    	if ( c2 == ' ' ) continue;
    	*c1++ = *c2;
    }
    while ( *(++c2) );
    
    *c1 = 0;
    

    }

  • Nall-ohki (unregistered) in reply to Nall-ohki

    Ack.

    Much better:

    void removeSpaces(char* c) { if ( ! c ) return;

    for ( char* ci = c; *ci; ci++ )
    	if ( *ci != ' ' )
    		*c++ = *ci;
    
    *c = *ci;
    

    }

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

Log In or post as a guest

Replying to comment #:

« Return to Article