• Michael (unregistered)

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

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

    }

  • (cs)

    Your implementation is not C++, is plain C.

  • Stiggy (unregistered)

    Apart from anything else, putting the required code in the Else section....

    The've not heard of NOT then.

  • jms (unregistered)

    Looks like the original code was in VB.NET... How about the following?

    string removedSpaces = origString.Replace(" ", String.Empty)

  • Not telling you... (unregistered)

    How about:

    new_string = edit$(old_string,2%)

    in VAX/DEC BASIC...

  • CrystalMethod (unregistered)

    I don't know what toy programming language that first example is (VB? Pascal?), byt surely the "ByVal" means the function is passed a copy of the string, and therefore has no change to the string in the caller?

  • Ade (unregistered) in reply to CrystalMethod

    In VB / VBA / VBS when you declare a function like this, the function name is also the name of the Variable whose value is returned, in this case the variable RemoveSpace will contain the string that is returned

  • CrystalMethod (unregistered) in reply to Sebastián

    Your implementation is not C++, is plain C.

    It is C++, just look at the way the conditionals are all the wrong way round, for example:

    '\0' != *from

    And the fact that like all C++ programmers he uses NULL despite being told to use 0 by all decent books on the language.

  • Doug (unregistered)

    I'd add :

    while ((to) && (*to++ != ' '));

    after the assignment of "to", and I'd change "from" to initialize to "to"

  • mav (unregistered) in reply to Sebastián
    Sebastián:
    Your implementation is not C++, is plain C.

    Because they're SO much different.....

  • mav (unregistered) in reply to Sebastián
    Sebastián:
    Your implementation is not C++, is plain C.

    Because C is SO MUCH different than C++ for some tiny little function like this.... C'mon. Seriously

  • Doug (unregistered)

    I'd change that to: char* RemoveSpaces( char *str ) { if ( NULL == str ) return NULL;

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

    }

  • Anonymous (unregistered)

    My version:

    char* RemoveSpaces( char *str ) { return RemoveSpaces(str); }

    Why won't it work!?!?! It says remove the spaces!

  • Anonymous Tart (unregistered)

    Virtually same algorithm, paramaterised the char to strip out, and more c-ified it.

    char* strip(char * src, char remove)
    {   
        char *p,*s; 
        p = s = src;
        for (; s && *s; ++s)
            if (remove != *s)
                *(p++) = *s;
        if (p)
            *p = '\0';
        return src;
    } 
    

    Your c++ one was interesting, in that it used C strings. A real C++ example would be..

    std::string&
    strip(std::string& str, const char remove)
    {
        str.erase(
            std::remove_if(str.begin(), str.end(), 
                    std::bind2nd(std::equal_to<char>(), remove)),
            str.end());
        return str;
    }
    
  • NateP (unregistered) in reply to CrystalMethod

    "I don't know what toy programming language that first example is (VB? Pascal?), byt surely the "ByVal" means the function is passed a copy of the string, and therefore has no change to the string in the caller?"

    You are correct that the incoming string is a copy but it is returning a string too...

    Private Function RemoveSpace(ByVal strFldName As String) As String ... RemoveSpace = RemoveSpace & Mid(strFldName, i, 1) ...

    In VB .NET, you "return" a value by setting the method name to a value so long as the method signature ends with AS [type]. If there is no "as [type]" it is essentially a void method.

  • (cs) in reply to Stiggy
    Stiggy:
    Apart from anything else, putting the required code in the Else section....

    The've not heard of NOT then.

    Maybe they're one of those paranoids who believes that IF NOT X THEN Y is less exclusive than:

    IF X THEN ... ELSE Y

    Believe it, I've met people who think that way.

  • Robin Barker (unregistered)

    perl: sub removeSpaces { $_[0] =~ s/ //g; }

    haskell: removeSpaces = filter (not . Char.isSpace)

  • cfreeman (unregistered)

    Perl:

    $str =~ s/ //g;

    Some things Perl was just meant to do.

  • hmmmm... (unregistered) in reply to CrystalMethod

    Yes, by design I should think since IT'S A FUNCTION (also look up the term "immutable"), ooooh these pesky "toy" languages can prove tricky can't they. ;-)

  • (cs) in reply to CrystalMethod
    CrystalMethod:
    I don't know what toy programming language that first example is (VB? Pascal?), byt surely the "ByVal" means the function is passed a copy of the string, and therefore has no change to the string in the caller?
    Anyone with half a brain would recognize that it's not pascal. It's obvious VB, that's the only (afaik) with ByVal...
  • pc (unregistered)
    	<xsl:template name="RemoveSpaces">
    		<xsl:param name="input" />
    		<xsl:variable name="space" select="' '" />
    		<xsl:choose>
    			<xsl:when test="contains($input, $space)">
    				<xsl:value-of select="substring-before($input, $space)"/>
    				<xsl:call-template name="RemoveSpaces">
    					<xsl:with-param name="input" select="substring-after($input, $space)" />
    				</xsl:call-template>
    			</xsl:when>
    			<xsl:otherwise>
    				<xsl:value-of select="$input"/>
    			</xsl:otherwise>
    		</xsl:choose>
    	</xsl:template>
  • Zekta (unregistered)

    So we are having fun of rewriting the function here's my copy

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

      char *from, *to;
      from=to=str;
    
      while ((*from != ' ') && (*to++=*from),
              *from++);
      return str;
    

    }

  • (cs) in reply to NateP

    I'm not sure what qualifies a programming language as a "Toy Language..." These days what makes a language "good" is its library support, and I'd say .NET is a nice library to have behind you.

    VB.net is not my favorite language, but its a far cry from being a "toy"

  • Josh (unregistered)

    Another case of why C++ will die. Why not add Replace to the standard string class? Is it really that controversial?

    Oh right the C++ standards committee doesn't actually do work.

  • Guy (unregistered) in reply to CrystalMethod

    Since a string in VB.Net is a reference type passing it ByVal is passing the value of the reference. The unmanaged equivalent would be passing a pointer to the string data. If you pass a string ByRef then you are passing a pointer to a pointer to the string data.

  • zach (unregistered)

    C++:

    #include <string>
    #include <algorithm>
    #include <iostream>
    #include <iterator>
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
       string str = "+hello+world++this+is+fun+";
       string out;
    
       remove_copy_if(str.begin(), str.end(), back_inserter(out),
                      bind2nd(equal_to<char>(), '+'));
       cout << out << endl;
       return 0;
    }
    
  • Phoenix (unregistered)

    Couldn't you use the C function: isalnum(int * a). I think that's how it's called. It would remove all the punctuation from the string too, but who needs punctuation?!

  • lf (unregistered) in reply to Robin Barker

    Why use a regex? $foo =~ tr/ //d is much faster

  • (cs) in reply to CrystalMethod
    CrystalMethod:
    It is C++, just look at the way the conditionals are all the wrong way round, for example:
    '\0' != *from
    I don't know how serious you are about that, but the main reason that I do that when programming in any language is to avoid the accident:

    if(a = 3) { ... }

    Which will compile fine. On the other hand:

    if(3 = a) { ... }

    Will fail right away. Even as an experienced programmer I occasionally make that mistake.

  • Anonymous (unregistered)
    void RemoveSpaces(char* str)
    {
      char* to = str;
      while(*str) {
        if (*str != ' ')
          *to++ = *str;
        str++;
      }
      *to = 0;
    }
  • cfreeman (unregistered)

    A better one in shell:

    This function sets the Env. Var 'RETURN'.

    Oh, and we overwrite 'tmp' and 'tmp.c'...

    function removeSpaces { cat > tmp.c <<HERE #include <stdio.h> int main(int argc, char **argv) { char *to = argv[1], *from = argv[1]; while( *from != '\0' ) { if( *to != ' ' ) *to++ = *from; from++; } fprintf(stdout, "%s", to); return 0; } HERE

    gcc -o tmp tmp.c

    RETURN=./tmp $* rm tmp tmp.c return [[ -n $RETURN ]] }

  • Jared (unregistered) in reply to Josh

    C++ string replace functions:

    http://www.cppreference.com/cppstring/replace.html

  • (cs) in reply to CrystalMethod
    CrystalMethod:
    And the fact that like all C++ programmers he uses NULL despite being told to use 0 by all decent books on the language.

    In a not-so-distant future the definition of NULL or even ZERO could change. I guess this one should be more compatible with future generation systems :

    if ( FILENOTFOUND == str ) return FILENOTFOUND;

    About the XSLT version : yep, I had to do it myself too, plain nightmare :|

    By the way here's the ruby version:

    s.gsub!(" ","") or s.gsub!(/ +/,"") ( don't know which one is faster )

    edit: this one should be faster : s.tr!(" ","")

  • jpvlsmv (unregistered) in reply to Anonymous

    Your code still has a bug in it. Here's the fixed version:

    charRemoveSpaces(charstr){return(RemoveSpaces(str));}

  • (cs)

    I tried to make this as easy as possible for the JavaScripters out there ;)

    function removeSpaces(str) {
      var newstr = [];
      for (var i = 0, len = str.length; i < len; i += 1) {
        if (!isSpace(str[i])) {
          newstr.push(str[i]);
        }
      }
      return newstr.join("");
    }
    function isSpace(char) {
      var reg = /\s/;
      return reg.test(char);
    }
    
  • cracki (unregistered)

    python:

    somestring.replace(" ", "")

    c:

    char *removespaces(char *s)
    {
    	char *p = s, *q = s;
    
    	do {
    		if (!isspace(*q))
    			*p++ = *q;
    	} while (*q++);
    
    	return s;
    }
    
    
  • Coolvibe (unregistered)

    Why not write it in such a way to make it character-agnostic:

    void
    stripchar(char *buf, int strip)
    {
            /*
             * strips every occurence of character buf from the string. is
             * destructive, works in situ.
             */
    
            char           *ptr = buf;
            int             len;
            char            c;
            len = strlen(buf) + 1;  /* adjust for \0 */
            while (--len > 0) {
                    c = *ptr++;
                    if (c != strip)
                            *buf++ = c;
            }
            *buf++ = '\0';
            return;
    }
    

    And then call

    stripchar(' ');
    . Also handy when you want to get rid of something else than spaces :)

    captcha: sanitarium (leave me beeee....)

  • Coolvibe (unregistered) in reply to Coolvibe

    Uhm, I of course mean

    stripchar(somestring, ' ');
    . :P

  • (cs) in reply to mav
    mav:
    Sebastián:
    Your implementation is not C++, is plain C.

    Because C is SO MUCH different than C++ for some tiny little function like this.... C'mon. Seriously

    Of course. It would be a method like String::RemoveSpaces and would use string and not char*

    Te fact that most people use C++ as C is because they don't know C++, but rather C with classes.

  • (cs) in reply to rbowes
    rbowes:
    CrystalMethod:
    It is C++, just look at the way the conditionals are all the wrong way round, for example:
    '\0' != *from
    I don't know how serious you are about that, but the main reason that I do that when programming in any language is to avoid the accident:

    if(a = 3) { ... }

    Which will compile fine. On the other hand:

    if(3 = a) { ... }

    Will fail right away. Even as an experienced programmer I occasionally make that mistake.

    Heres a dime, now get yourself a better compiler.

  • (cs) in reply to treefrog
    treefrog:
    I tried to make this as *easy* as possible for the JavaScripters out there ;)
    Are you morally opposed to the replace function or regexp or something?

    function removeSpaces(str) var newStr = str.replace(/ /g, //); return newStr; }

  • grumble (unregistered) in reply to rbowes
    rbowes:
    if(a = 3) { ... }

    Which will compile fine. On the other hand:

    if(3 = a) { ... }

    Will fail right away. Even as an experienced programmer I occasionally make that mistake.

    Ah, I was going to ask why the reversed conditional in the original, nifty trick.

    Captcha: tastey. Yes in deed. Learning tastes goood (even if it can't spell)

  • (cs)

    Derrick's original code really is C++, not C, because the "char * to = str;" line came AFTER the "if( NULL == str )" line, which would fail under C.

    also, I'd never write a line quite as heinous as while ((*to) && (to++ != ' ')); Compiler decipher code; humans should never have to. Particularly, when that line could easily have been written: char to = strchr(str, ' ');

    But, that bring us to another important point... What about tabs and other forms of whitespace? Has no one heard of isspace()?

    const char End_of_String = '\0'; #define NULL 0

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

    char* from = str ;
    
    while (*from != End_of_String && !isspace(*from))
    {
    	++from;
    }
    
    char* to = from;
    
    while (*from != End_of_String)
    {
    	if (!isspace(*from))
    	{
    		*to = *from;
    		++to;
    	}
    	++from;
    }
    
    *to = End_of_String;
    return str;
    

    }

  • (cs) in reply to JamesCurran
    JamesCurran:
    Derrick's original code really is C++, not C, because the "char * to = str;" line came AFTER the "if( NULL == str )" line, which would fail under C.

    Not in C99 if I'm not mistaken.

  • meak (unregistered)
    removeSpaces = filter (' ' /=)
  • Tchakkazulu (unregistered)

    Some Haskell:

    removeSpaces = filter (/= ' ')

  • (cs)

    Since this code is VB.NET it would just have been string.Replace(" ", "") The try catch is probably there for when the argument is null (Nothing in VB?) so that the function will return an empty string.

  • badman (unregistered)

    Here's a bad one:

    removespaces s = if count ' ' s > 0 then yes ++ removespaces rest else s
     where count c str = length [ x | x <- str, x == c  ] 
           (yes,mid) = span (/= ' ') s
           (_,rest)  = span (== ' ') mid
    
  • cracki (unregistered) in reply to cracki

    also:

    char *removespaces(char *s)
    {
      char *p = s, *q = s;
      if (!s) return 0;
      while (!isspace(*q) && (*p++ = *q), *q++);
      return s;
    }
  • Mike (unregistered)

    I'd like to put forward the first recursive version noted here (obviously this is for the more advanced programmers among us). It works brillantly, but some users report that with long strings they get some kind of stack error (a bug in the C# framework I suspect).

    static string RemoveSpace(string text)
    {
        if (text.StartsWith(" "))
            text = text.Substring(1);
        if (text.Length == 0)
            return "";
        return text[0] + RemoveSpace(text.Substring(1));
    }
    

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

Log In or post as a guest

Replying to comment #:

« Return to Article