• aaron (unregistered)

    I've actually done this on an occasion or two:

    <?php
    $stringToDeSpace = strreplace(" ", "", $stringToDeSpace);
    ?>
    

    But if we MUST do it iteratively

    <?php
    for ($i = 0; $i < strlen($stringToDeSpace); $i++)
    {
        $testVal = substr($stringToDeSpace,$i,1);
        if ($testVal !== " ") $output .= $testVal;
    }
    ?>
    

    captcha: tesla -- the REAL man you can thank everytime you turn on your light switch. (If edison had his way, we'd all have DC generators in our basements, chugging away fossil fuels!)

  • noone (unregistered) in reply to rbowes
    rbowes:
    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.

    This style is no longer necessary as any reasonably modern compiler can throw a warning or error if you type "if (a = 3)" instead of "if (a == 3)". In fact, suppose you were testing if a equals b. Will this style protect you?

    if (a = b) if (b = a)

    Nope, the style fails to offer any protection. A compiler on the other hand will catch that error. And in the off chance you need to do an assignment and a test in one step, you simply use the following:

    if ((a = b) == 0)

    Compiler lets it through clean and it is very clear the assignment is intended.

  • lol (unregistered)

    In delphi:

    MyString:= StringReplace(MyString, ' ', '', [rfReplaceAll]);

    Yes, you can actually use the same string to remove the spaces, and put it back. None of this lame-assed temp variables.

  • CrazyJo (unregistered) in reply to mav

    Well, it IS very much different in C++. In C++, you would use std::string and iterators, not raw char * pointers.

  • DKO (unregistered) in reply to Jared
    Jared:
    C++ string replace functions:

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

    Which are useless in this case. I would use Boost.Regex or Boost.String_algo.

  • (cs)

    Maybe it is just me, but this seems awfully trivial...

    Isn't it?

    IMEANSRSLYGUYS.

  • (cs) in reply to GeneWitch

    Also, in ti-84/A BASIC:

    (starting wherever)

    100 a = len(sring1$) 110 for i = 0 to a step 1 120 if left$(string1$, i) = " " then left$(string1$, i) = "" 130 next i 140 end

    haha.

  • (cs) in reply to pc
    pc:
    	<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>
    You beat me to the punch!!! Good job.
  • nausea (unregistered)

    If someone submitted this as a WTF, they shouldn't be working on the code. It seems to be some code migrated from VB6, which didn't have the .Replace functionality (if I remember correctly). The above function was actually a reasonably efficient way to remove spaces from a string in VB6. In .Net, you could of course just write the entire function as:

    myString.Replace(" ", "")

  • facetious (unregistered)
    1. string =~ s/ //g; [perl]
    2. string.replace(" ","") [python]
    3. string = "".join(string.split(" ")) [python]
    4. string = filter(lambda x: x != " ",string) [python]
  • (cs)

    This all would have been much more interesting if the task was instead to remove all EXTRA spaces, leaving only single spaces, if any.

  • (cs)

    Obviously:

    char *removeSpaces(char *txt)
    {
       int times = strlen(txt);
    
       while(times--) {
          int i = rand() % strlen(txt);
          if(txt[i] == ' ') {
             strcpy(&txt[i], &txt[i + 1]);
          }
       }
    }
    

    Plug and pray...

  • zach (unregistered) in reply to Zylon

    in perl: $var ~= s/\s+ / /g;

  • Mike (unregistered) in reply to nausea
    nausea:
    If someone submitted this as a WTF, they shouldn't be working on the code. It seems to be some code migrated from VB6, which didn't have the .Replace functionality (if I remember correctly).

    Nope, VB6 did have a method called 'Replace' which does exactly what we want it to.

  • NNNN (unregistered)

    Haskell version:

    removeSpaces = filter ' '

  • NNNN (unregistered)

    Haskell version:

    removeSpaces = filter (==' ')

  • fman (unregistered) in reply to Mike
    Mike:
    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));
    }
    

    This will fail for strings with two or more consecutive spaces. Thankfully, this is easy to fix with a helper function:

    static string removeAllSpaces(string text) {
        if (text.contains(" "))
            return removeAllSpaces(removeSpace(text));
        else
            return text;
    }
    
  • dnm (unregistered)

    tr/ //d;

  • EmmanuelD (unregistered)

    The same function in the WhiteSpace language:

    This is copied from a paper sheet (you know, the trick they explained to keep your source code secret: print your source code, delete the source code file; if you ever need to redo it, just copy what's written on your printed version).

    I haven't tested it, so maybe it doesn't work exactly as expected.

  • David Wolever (unregistered) in reply to LizardKing
    LizardKing:
    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.

    Heres a dime, now get yourself a better compiler.

    ... I'm confused. How is a compiler that can assign the value of 'a' to the integer '3' BETTER than one that will refuse?

  • cj (unregistered)
      1* SELECT :C, REPLACE( :C, ' ', NULL ) FROM DUAL
    SQL>/
    
    :C                               REPLACE(:C,'',NULL)
    -------------------------------- --------------------------------
    THIS IS A TEST                   THISISATEST
    
  • (cs)
    From Randy,

    I don't even know what the hell the Try/Catch is supposed to be doing, not to mention that the programmer expanded a (typically) one-line operation to thirteen plus a number extra function calls and boolean logic.

    I really hope thats <sarcasm>, can't see how anyone could could miss the overflow exception when i = strFldName.Length

  • Eric (unregistered)

    fun removeSpaces y = concat (map (fn x => if x = " " then "" else x) y);

    obviously that isn't quite right, but i'm a bit rusty.

  • (cs)

    Since we're publishing our own implementations, here's mine.

    Q&D, with comments for you HLL programming n00bs

          LA  R1,TEH_STRING-1         R1-FROM PTR
          LA  R2,TEH_STRING           R2-TO PTR
    LOOP1 EQU *
          LA  R1,1(R1)                NEXT FROM CHAR
          CLI 0(R1),X'00'             END-OF-STRING?
          BE  ENDLP                   YES, ADD IN NULL AND EXIT
          CLI 0(R1),C' '              SPACE?
          BE  LOOP1                   YES, IGNORE IT AND LOOP
          MVC 0(1,R2),0(R1)           MOVE CHARACTER
          LA  R2,1(R2)                NEXT TO CHAR
          B   LOOP1
    ENDLP EQU *
          MVI 0(R2),X'00'             END OFF WITH NULL
    
  • dnm (unregistered)

    zac: Yours is extraneous.

    s/\s+//g means match any space of 1 or more characters, and replace it with nothing globally.

    Just s/\s//g would do the same.

  • pc (unregistered) in reply to nausea
    nausea:
    If someone submitted this as a WTF, they shouldn't be working on the code. It seems to be some code migrated from VB6, which didn't have the .Replace functionality (if I remember correctly). The above function *was* actually a reasonably efficient way to remove spaces from a string in VB6.

    You mean VB5. Replace was added in VB6 (and I remember being very happy at the time due to that new feature).

  • Reed Hedges (unregistered)

    Thank you Anonymous Tart and Zach for the real C++ approach.

    My feeble attempt at scheme

    Assuming strings are lists of characters.

    A simple recursive search:

    (define remove-spaces (lambda (s) ( (cond (empty? s) s (cond (eq? (car s) " ") (remove-spaces (cdr s)) (cons (car s) (remove-spaces (cdr s))) ))

    Or use a predefined filter function

    (define remove-spaces (lambda (s) ( (filter (lambda (c) (not (eq? c " "))) s) ))

    I think this is a correct definition of filter?

    (define filter (lambda (pred list) ( (cond (empty? list) list (cond ((pred) (car list)) (cons (car list) (filter pred (cdr list)) (filter pred (cdr list))) ))

  • Bob (unregistered)

    IF sentence has space THEN remove space THANKS

  • bigjim (unregistered)

    I think nausea and a few others found the right way to do this in vb.net:

    Private Function RemoveSpace(ByVal strFldName As String) As String RemoveSpace = strFldName.Replace(" ","") End Function

    some things the Framework was just meant to do...

  • Zeta Reticuli (unregistered)
    char* remove_char(char *s, char c) {
    	const char *os = s, *t = s;
    
    	while (*t != '\0') {
    		while (*t == c) ++t;
    		*s++ = *t++;
    	}
    	*s = '\0';
    
    	return os;
    }
    

    IMO, this version is clearer than most others, because the only statement that's not completely boilerplate is the line

    	while (*t == c) ++t;
    

    which skips runs of the character we should remove. The rest is a boilerplate string copy loop.

    "cracki", I hope you don't write actual code that way. Just because any C programmer should understand it doesn't mean it's maintainable.

  • Zeta Reticuli (unregistered) in reply to David Wolever

    He means that any compiler written after 824 B.C. will emit a warning when you do something silly like "if (a = 3)", and any compiler written after 522 B.C. will have an option to turn that warning into an error.

    Of course, this is far from a perfect stupidity guard because plenty of programmers ignore compiler warnings, and would never dream of making them errors because they simply don't know how to make all those warnings go away. C is hard.

    In fairness, some libraries and APIs are broken enough to practically require you to ignore some warnings. Nevertheless, "possibly incorrect assignment" is not one you should miss.

  • woah! (unregistered) in reply to dnm
    dnm:
    zac: Yours is extraneous.

    s/\s+//g means match any space of 1 or more characters, and replace it with nothing globally.

    Just s/\s//g would do the same.

    It would do the same, but it would be slower for many circumstances. For example, given the string:

    'XXfooXXXXXbarXXXbazz'

    using s/X+//g would make the regex engine complete three replacements, where using s/X//g would cause the regex engine to net ten replacements.

    So it is definitely NOT extraneous.

    Captcha: ewww

  • Eric (unregistered)

    I'm surprised nobody mentioned it already, but the simple example function makes me cringe. I never trust a string to be properly terminated in C. I nt his day and age, with buffer overflow being the rage with all the script kiddies, I never use strcpy, using strncpy instead. So I'd like to say that all those functions are nice, but as a defensive programmer I would always implement this function with the signature

    char* remove_spaces(char *str, unsigned maxlength);

  • WTG (unregistered)

    euh .. obviously

    Function RemoveWhiteSpace(text as String) as String If text = Null Then Return Null Return text.Replace(" ", "") End Function

    captcha: scooter

  • BF (unregistered) in reply to ParkinT
    ParkinT:
    pc:
    	<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>
    You beat me to the punch!!! Good job.
    Two full pages of re-implementations and not one in brainfuck?
  • JC (unregistered) in reply to Not telling you...
    Not telling you...:
    How about:

    new_string = edit$(old_string,2%)

    in VAX/DEC BASIC...

    But this would remove the tabs too...

    (overcoming surprise that there is another VAX/DEC/Compaq/HP/Alpha/Integrity(*) BASIC programmer reading this site!)

    (*) delete where appropriate

  • (cs)

    DKO has got the right idea for C++. It's as simple as

    std::string input = "This string has spaces.";
    boost::algorithm::erase_all(input, " ");

    Really knowing a language for efficient programming largely means knowing the available libraries, and Boost is a library collection no C++ programmer can afford to ignore.

  • BF (unregistered) in reply to ParkinT
    ParkinT:
    pc:
    	<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>
    You beat me to the punch!!! Good job.
    Hmmm, two full pages of re-implementations and not one in brainfuck? You guys are slipping!
  • protonfish (unregistered)
    Otto:
    Are you morally opposed to the replace function or regexp or something?

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

    Here is a javascript function that is one line and actually works:

    function removeSpaces(str) {
      return str.replace(/ /g, "");
    }

    Javascript can be used for good. Please don't mock a perfectly acceptable language just because it is abused by script kiddies.

  • Mhendren (unregistered)

    My version

    static char *remove_spaces (char *s)
    {
            char *p;
            char *d;
            int t;
            for (p = s, t = strlen (p); (p - s) <= t; p++)
            {
                    if (!strncasecmp (p, " ", 1))
                    {
                            int q;
                            char *z;
                            d = strdup (remove_spaces (p + 1));
                            for (z = d, q = strlen (z); (z - d) <=  q; z++)
                                    p[(z - d)] = *z;
                            free (d);
                    }
            }
    
            return s;
    }
    
  • CynicalTyler (unregistered)

    I prefer to use this handy little tool for removing spaces. Sure, it's a little finicky, maybe sometimes downright rude, but it's how we've always done it...

    package wtf.cynicaltyler;
    
    //This class is totally rad!
    public class StringTool {
       private String string = null;
    	
       public StringTool(String string) throws
          NullPointerException {
          if(string == null)
             throw new NullPointerException(
                "I pity the fool who initializes "+
                "StringTool with a null string!");
             this.string = string;
       }
    	
       public String removeSpaces() {
          CharWalkerDemon beelz = new CharWalkerDemon();
          beelz.feedSpacesToDemon();
          string = beelz.prayToDemonForSafeReturnOfTheString();
          return string;
       }
    	
       protected class CharWalkerDemon {
          private boolean done;
          private boolean angry;
          private char[] chars;
          private int currentIndex;
    		
          protected CharWalkerDemon() {
             done = false;
             angry = false;
             currentIndex = 0;
             chars = string.toCharArray();
          }
    		
          protected void feedSpacesToDemon() {
             if(done) {
                angry = true;
             } else {
                angry = true;
                for(int currentindex = chars.length;
                   currentindex > 0; currentindex--) {
                   if(walk() == ' ') {
                      consume(--currentIndex);
                      angry = false;
                   }
                }
                done = true;
             }
          }
    		
          protected String prayToDemonForSafeReturnOfTheString() {
             if(done && !angry) {
                return new String(chars);
             } else if(!done || angry) {
                return wrath();
             } else {
                //TODO
                return null;
             }	
          }
    
          private char walk() {
             return chars[currentIndex++];
          }
    
          private void consume(int index) {
             char[] temporaryCharacterArray = new char[chars.length-1];
             boolean skip = false;
             for(int i = 0; i < chars.length-1; i++) {
                if(i == index) {
                   skip = true;
                }
                if(skip) {
                   temporaryCharacterArray[i] = chars[i+1];
                } else {
                   temporaryCharacterArray[i] = chars[i];
                }
             }
             chars = temporaryCharacterArray;
          }
    
          private String wrath() {
             chars = new char[] {'F','O','O','L','I','S','H',
                ' ','M','O','R','T','A','L','!'};
             return new String(chars);
          }
       }
    }
    

    If anyone's interested in seeing some examples of how this is used I'd be happy to provide. >:)

  • Matthew Watson (unregistered) in reply to cfreeman
    cfreeman:
    Perl:

    $str =~ s/ //g;

    Some things Perl was just meant to do.

    But legibility is presumably not one of those things. O.o

    Captcha: Mmmm waffles.

  • Jeff (unregistered)

    // With 'char *s' *std::remove(s, s + strlen(s), ' ') = 0;

    // With 'std::string s' s.erase(std::remove(s.begin(), s.end(), ' '), s.end());

    Pretty ugly, I admit, but it's the standard library so anyone fluent in C++ should understand it.

  • AndyO (unregistered)

    OK, I will start writing some object oriented class including some design patterns for this task...

  • CrankyPants (unregistered) in reply to nausea

    I know in vbs it can be done with:

    Replace("This Is A Test String", " ", "")

    I'd be surprised if other VB implementations didn't have anything similar.

  • (cs) in reply to Michael

    Unfortunately I'm not at my dev machine and I don't remember much without being sat at it, but here's my walk through of a great way to do it.

    1. create a copy of the string to be altered (incase there is a problem!

    2. create a var that can be used later.

    3. pass the copied string text, character by character through a function that looks for " " and strips it out of the temporary var.

    4. if that went ok, pass the temp var as the result

    psuedo code:

    function strip_white_space(start_string: string;) result; var copy_str, temp_str : string; str_pos : integer; end;

    copy_str := start_string; str_pos := 0; for str_pos < copy_str.length {

    if copy_str.text[str_pos] !=" " then temp_str.text := tempstr.txt + copy_str.text[str_pos] else end;

    result := tempstr; }

    end;

    Please please please, don't badger me about my bad coding, I'm good enough to know not to put anything like the above out in production!

  • SirisC (unregistered)
        Private Function RemoveSpace(ByVal a As String)
            If a Is Nothing Then
                Return ""
            End If
            Dim b(Len(a)) As Char
            Dim c As Integer
            For c = 1 To Len(a)
                Dim d As String
                d = Mid(a, c, 1).ToCharArray(0, 1)
                b(c - 1) = d
            Next
            Dim e As String
            e = ""
            Dim f As Char
            For Each f In b
                If f = " " Then
                    e = e
                Else
                    e = e + f.ToString
                End If
            Next
            Return e
        End Function
  • mjb (unregistered) in reply to nausea

    Actually VB6 DOES have Replace

  • Richard (unregistered)

    newstr = ''.join(oldstr.split('+'))

  • Maks Verver (unregistered)

    The original code is especially bad since the standard explicitely forbids the source and destination strings for strcpy() to overlap. (If the strcpy() implementation is optimized to copy several bytes at a time, this code goes horribly wrong; presumably, it happens to work on their particular platform.) For overlapping buffers, there is memmove(), but it requires the string length as an argument.

    The C++ example isn't really C++. A sort-of functional way to write this in C++ would be:

    *std::remove_if(s, s + strlen(s), bind2nd(equal_to<char>(), ' ')) = 0;
    It's short and it's reasonably efficient (O(N)), but it's not very clear. I'd rather go for one of the more elegant C solutions using two pointers in a loop.

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

Log In or post as a guest

Replying to comment #:

« Return to Article