• Faxmachinen (unregistered)
    void RemoveSpace( string *src, string *dst )
    {
    	int i;
    
    	dst->clear();
    
    	// Find all the spaces in src
    	vector<int> spaceindex;
    	spaceindex.push_back(src->size());
    	for
    	(
    		i = src->rfind(' ', src->size());
    		(i != string::npos) && (i > 0);
    		i = src->rfind(' ', i - 1)
    	)
    		spaceindex.push_back( i );
    
    	// Write everything except spaces to dst
    	vector<int>::iterator vi;
    	for
    	(
    		vi = spaceindex.begin();
    		vi != spaceindex.end();
    		vi++
    	)
    	{
    		if (vi + 1 == spaceindex.end())
    			dst->insert(0, src->substr( 0, *vi ));
    		else
    			dst->insert( 0, src->substr( *(vi + 1) + 1,	*vi - *(vi + 1) - 1));
    	}
    }
  • Rob (unregistered) in reply to pc
    <xsl:template name="RemoveSpaces">
    	<xsl:param name="input" />
    	<xsl:value-of select="translate($input, ' ', '')"/>
    </xsl:template>
    
  • (cs)

    Okay, since character comparison is an highly time-consuming operation, we should think about a multithreaded version to take full advantage of massively parallel architectures.

    So, here is my multithreaded ruby version. Each thread processes a single character : that couldn't be more optimal when string length is equal to the size of the cluster.

    require 'thwait'
    
    class String
      def remove_spaces!
    
        result = []
        threads = []
    
        length.times do |i|
          threads << Thread.new(i,self[i,1]) do |index,character|
            result[index] = character if !character.eql? " "
          end
        end
    
        ThreadsWait.all_waits threads
        replace result.join
      end
    end
    
    print "      hello           world             ".remove_spaces!
    
  • dp.design (unregistered) in reply to Bob
    Bob:
    IF sentence has space THEN remove space THANKS

    I lol't.

    std::string vacuum(std::string s)
    {
    	for (int c = 0; c < s.length(); c++)
    		if (isspace(s[c]))
    			s.erase(c, 1);
    	return s;
    }
  • Anonymouse >°.°< (unregistered)

    Here's my version of this function, written completely in Whitespace. It was going to be written as a one-liner, but that would have caused the page to scroll horizontally quite a bit, so it's been split up into multiple lines.

    Removes spaces from input.
                                                          
                                                          
                                                            
                                                             
                                                              
                                                              
                                                              
                                                              
                                                              
                                                              
                      
  • Anonymous (unregistered) in reply to Rob
    Rob:
    <xsl:template name="RemoveSpaces">
    	<xsl:param name="input" />
    	<xsl:value-of select="translate($input, ' ', '')"/>
    </xsl:template>
    

    Sure, but it's not so easy as that for those of us who don't have the translate function available!

    Here's elisp, which I don't see represented here too much:

    (require 'string)
    (string-replace-match (regexp-quote " ") "this is my string" "" nil 1)
    
  • Michael (unregistered)

    The quantum computing version:

    function RemoveSpaces(qstring stringWithOrWithoutSpaces) { // Collapse variable waveform to non-spaced string form. stringWithOrWithoutSpaces.contains(" ") = false;

    return stringWithOrWithoutSpaces; // No longer has spaces.
    

    }

    Runs in -3ns, beat that Ruby!

  • (cs) in reply to Michael

    Recursive, mixes std::string and char* for no good reason, wastes object creation like mad. Has some fun times converting between string and stringstream representations. All it needs is random templating and it could become the best code ever written...

    std::string removeSpacesAux( char* str ) { std::stringstream stream;

    if( str[0] == '\0' )
        stream << str[0];
    else if( str[0] == ' ' )
        stream << removeSpacesAux( str+1 );
    else
        stream << str[0] << removeSpacesAux( str + 1 );
    return stream.str();
    

    }

    const char* removeSpaces( char* str, char *out ) { std::string removed = removeSpacesAux( str ); strcpy( out, removed.c_str() ); return out; }

  • Rhamphoryncus (unregistered)

    In Python:

    s = s.replace(' ', '')
    Too boring I guess.

  • facetious (unregistered) in reply to Anonymouse >°.°<
    Anonymouse >°.°<:
    Here's my version of this function, written completely in Whitespace. It was going to be written as a one-liner, but that would have caused the page to scroll horizontally quite a bit, so it's been split up into multiple lines.
    Removes spaces from input.
                                                          
                                                          
                                                            
                                                             
                                                              
                                                              
                                                              
                                                              
                                                              
                                                              
                      

    Hard returns are meaningful in WhiteSpace - it is not just spaces. In fact, you don't even have any tabs in there. I call BS.

  • In php.... (unregistered)

    function removeSpaces(&$_string){ strtr($_string, " ",""); }

  • (cs) in reply to Michael
    Michael:
    The quantum computing version:

    function RemoveSpaces(qstring stringWithOrWithoutSpaces) { // Collapse variable waveform to non-spaced string form. stringWithOrWithoutSpaces.contains(" ") = false;

    return stringWithOrWithoutSpaces; // No longer has spaces.
    

    }

    Runs in -3ns, beat that Ruby!

    Ahah!

    Well, in a real enterprisey environment, everything is configurable, even values for TRUE, FALSE, ZERO or even FILENOTFOUND.

    So, just insert that line in the beginning of the file :

    " " = ""

  • vermeil (unregistered)

    Lisp:

    (remove #\Space s)

  • Botzinger Gulm (unregistered)

    It's not quite one-liner but close.

    void strnfilter(char* str, int c, size_t n)
    {
    	char *from = str, *to = str;
    	size_t max_count = n;
    	if ( str ) { while ( max_count-- && (*(to += *to != c) = *from++) ); *to = 0; }
    }
    

    The real wtf is the number of dumb people who don't know that newlines are part of Whitespace syntax and still try to be funny with it. Muhahaha.

  • foo (unregistered)

    Do we get bonus point for obfuscation?

    void foo(char *in, char *out) { while(*out++=in==' '?++in:*in)in++; }

  • lars (unregistered)
    main(int argc, char *argv[])
    {
      /* Safety check */
      if (argc != 2)
        return;
    
      (*argv[1]!=' ')&&!putchar(*argv[1])?0:main(argc,(++argv[1],argv));
      
    }
    

    That's even without evilness...

  • Nobody (unregistered)

    Why check each letter when you can split and append! :)

    private string RemoveSpaces(string s) { string[] removedspaces; string results = string.Empty; int count = 0; int i = 0;

                 removedspaces = s.Split(new Char[] { ' ' });
                 count = removedspaces.Length;
    
                 do
                 {
                     results = results +      removedspaces[i].ToString();
                     i++;
                 } while (i < count);
    
                 return results.ToString();
        }
    
  • wayne (unregistered) in reply to treefrog
    treefrog:
    I tried to make this as *easy* as possible for the JavaScripters out there ;)

    How about this one? :-)

    String.prototype.removeSpaces =  function() {
    	var buffer = this;
    	while(buffer.indexOf(" ") >= 0) {
    		buffer = buffer.substring(0, buffer.indexOf(" ")) + buffer.substring(buffer.indexOf(" ") + 1, buffer.length);
    	}
    	return buffer;
    }
    
    alert("Hello World!".removeSpaces());

    captcha: dreadlocks - the new spaghetti?

  • (cs) in reply to Otto

    I forgot the <sarcasm> tags surrounding my code ;)

  • (cs) in reply to wayne
    wayne:
    treefrog:
    I tried to make this as *easy* as possible for the JavaScripters out there ;)

    How about this one? :-)

    String.prototype.removeSpaces =  function() {
    	var buffer = this;
    	while(buffer.indexOf(" ") >= 0) {
    		buffer = buffer.substring(0, buffer.indexOf(" ")) + buffer.substring(buffer.indexOf(" ") + 1, buffer.length);
    	}
    	return buffer;
    }
    
    alert("Hello World!".removeSpaces());

    captcha: dreadlocks - the new spaghetti?

    Very nice! I'm sure we could figure out a way to really obfuscate this.

    Why not build this as a js object, make it dependent upon the prototype libary, and increase the user download 10-fold so we can remove spaces from a string? LOL

    I like how creative some of the replies have been to turn a simple string replacement into something funny.

  • protonfish (unregistered)

    Haven't you people heard of Web 2.0? Everything is in ajax now!

    function removeSpaces(stringWithSpaces) {
      var ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
      ajaxObject.open("POST", "removespaces.php", false);
      ajaxObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      ajaxObject.send("s="+stringWithSpaces);
      return ajaxObject.responseText;
    }

    removespaces.php:

    print str_replace(' ', '', $_POST['s']);
  • Russ (unregistered) in reply to Michael

    ColdFusion:

    function removeSpaces(string) { return Replace(string," ",""); }

    Some things ASP.NET and C were just not meant to do...

  • (cs)

    VB6

    Private Function RemoveSpaces(Value As String) As String
    
        Dim strCharArray() As String
        Dim intIndex As Integer
        Dim strFormat As String
        
        ReDim strCharArray(Len(Value))
        
        For intIndex = 1 To Len(Value)
            If (Mid(Value, intIndex, 1) = " ") = True Then
                strCharArray(intIndex) = "DELETEME"
            Else
                strCharArray(intIndex) = Mid(Value, intIndex, 1)
            End If
            DoEvents
        Next
        
        For intIndex = 1 To UBound(strCharArray)
            If InStr(strCharArray(intIndex), "DELETEME") = 0 Then
                strFormat = strFormat & strCharArray(intIndex)
            End If
            DoEvents
        Next
    
        RemoveSpaces = strFormat
    
    End Function
    
  • SkittlesAreYum (unregistered) in reply to CynicalTyler

    I got a big kick out of that, thanks. Who doesn't like Char Walker Demons?

  • HorrifiedByXSL (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.

    choose? when? OTHERWISE?!! WTF?! Haven't the 'genius' creators of xsl ever heard of 'if', 'else', or 'switch' statements which are the de facto standard control statements for almost every other modern language?

    I dread the day that I am forced to use such a convoluted, designed-by-committee, half-assed, angle-bracket, wanna-be programming language. It actually looks worse than ColdFusion!! And that's saying something!

  • (cs) in reply to protonfish
    protonfish:
    Haven't you people heard of Web 2.0? Everything is in ajax now!

    Ahah, excellent.

    But then again, you really need to parallelize that time-consuming character comparison process and take advantage of your load balancer. I suggest you send one ajax request per character ( and send them simultaneously, indeed, don't wait between each character ) and asynchronously rebuild the whitespaceless string. This has to be absolutely optimal. Too bad I'm too busy right now, must be entertaining.

    I wonder if an haskell guy can figure out a similar parallel network-enabled implementation.

  • mathew (unregistered)

    Obligatory Ruby version:

    class String
      def remove_spaces
        self.gsub(' ','')
      end
    end
    
    puts "Look, I extended the core String class!".remove_spaces
  • Space Invader (unregistered) in reply to Nobody
    sub ReplaceString {
       my $str = shift(@_)
       return join "", grep {!/ /} split "", $str;
    }
    

    captcha: bathe -- somehow I feel dirty

  • (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.

    Really? Even as a newbie programmer I almost never made that mistake. I think I recall once, about ten years ago, starting to make it, catching myself before I finished typing the line, and backspacing to correct it.

    I've always thought this was mostly a myth. I consider if (3 == a) to be fairly silly.

  • (cs) in reply to HorrifiedByXSL
    HorrifiedByXSL:
    I dread the day that I am forced to use such a convoluted, designed-by-committee, half-assed, angle-bracket, wanna-be programming language. It actually looks worse than ColdFusion!! And that's saying something!

    This is braindead but XSL is not really a programming language. It's used for document transformations. Still, I think it's okay to use it for a RSS to XHTML conversion, for instance ... but it's so limited and still complicated, I don't know if it really makes a sense to learn it. It's so early-00's-let's-express-everything-in-XML ...

  • (cs) in reply to Zylon

    Real Programmers use Prolog:

    is_not_space(Char):-	\+ char_type(Char,space).
    despace(Spaced,Despaced):-	sublist(is_not_space,Spaced,X), string_to_list(Despaced,X).
    

    In SWI-Prolog we get:

    47 ?- despace("This is a string!",X).
    X = "Thisisastring!" 
    Yes
    
    Zylon:
    This all would have been much more interesting if the task was instead to remove all EXTRA spaces, leaving only single spaces, if any.
    Not in Ruby:
    str.squeeze! ' '
    
  • jrockway (unregistered) in reply to Anonymous
    Anonymous:
    My version:

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

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

    Close. Try this:

    removeSpaces [] = [] removeSpaces (x:xs) = if isSpace x then removeSpace xs else x : removeSpaces xs

  • protonfish (unregistered)
    aikii:
    But then again, you really need to parallelize that time-consuming character comparison process and take advantage of your load balancer. I suggest you send one ajax request per character ( and send them simultaneously, indeed, don't wait between each character ) and asynchronously rebuild the whitespaceless string. This has to be absolutely optimal. Too bad I'm too busy right now, must be entertaining.

    I'd rather parallelize server side only so I can expose the front end as a Web service to create mashups when aggregating the tubes. This is my plan to become the next Internet millionaire: www.spaceremovr.com. Now all I need is some venture capital . . .

  • (cs)
    RemoveSpaces
        ld d,h
        ld e,l
    -   ld a,(hl)
        inc hl
        or a
        ret z
        cp ' '
        jr z,-
        ld (de),a
        inc de
        jr -
  • (cs) in reply to JamesCurran
    JamesCurran:
    But, that bring us to another important point... What about tabs and other forms of whitespace? Has no one heard of isspace()?

    Congratulations, you've actually managed to turn what was merely a WTF into something that's actually broken.

    The original function only replaced spaces. With nothing else to go on (no documentation to the contrary, for example), we can only assume that it was MEANT to only replace spaces, and not tabs, carriage returns, line feeds, vertical tabs (!), or anything else. Your version changes the semantics of the function.

    Apparently the thinking here is, "Man, that is some messed up code, I could rewrite that to be a lot simpler, clearer, and more readable. Oh, and, also, that guy is only removing spaces, that must be because he didn't know how to handle tabs and other whitespace (I mean, just look, he could barely handle writing the version that just removes the spaces), so I'll help him out by changing it so that it removes all whitespace, not just spaces." WTF?

  • Stan (unregistered)

    REXX is still one of my favorites. It has lots of "word" functions ...

    sentence = space(sentence,0)

    The 2nd parameter is the number of spaces between words, defaults to 1. The 3rd parameter (not shown) is the pad character, defaults to blank.

  • (cs) in reply to protonfish

    I'll give you ten million dollars, but you have to buy lots of Aeron chairs and a cappucino machine.

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

    Feel free to point out deficiencies in a language, but don't just make up stuff. C++'s string class DOES have a replace function (several variations of it, in fact): basic_string

  • dustin (unregistered)

    string RemoveSpace(string s) { char[] c = s.ToCharArray(); for(int n=0; n < c.Length; n++) { if (' ' == c[n]) { c[n] = '-'; } } return(new string(c)); }

    // my programs in school often did what the assignment asked but not what the teacher wanted.

  • Zygo (unregistered) in reply to cfreeman
    cfreeman:
    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 ]] }

    Or just

    removeSpaces () { echo "${1// /}"; }

    since you would probably use this like so:

    val="removeSpaces "foo bar ""

  • (cs) in reply to Michael

    Mine takes advantage of the Dictionary generic from .NET 2.0. The dictionary is indexed by each unique character in the string, with the value for each item being a list of all occurrences of that character. That way you don't have to do a bunch of compares when there are multiple occurrences of the one you want to remove. Isn't that efficient? :)

    
    public static string RemoveCharFromString(string text, char charToRemove)
    {
    	//Convert the character to remove to a string
    	string removeToken = string.Format("{0}", charToRemove);
    			
    	//Create a dictionary to hold the index of each character in the string
    	Dictionary<string, List<int>> charIndex = new Dictionary<string, List<int>>();
    
    	//Index the positions of unique character in the string
    	for (int i = 0; i < text.Length; i++)
    	{
    		string current = text.Substring(i, 1);
    		if (!charIndex.ContainsKey(current))
    		{
    			charIndex.Add(current, new List<int>());
    		}
    		charIndex[current].Add(i);
    	}
    
            //Store a list of the characters that are to be included in the final string
    	SortedList<int, int> charPositionList = new SortedList<int, int>();
    
    	//Iterate the index of characters, only excluding the one that matches the removeToken
    	foreach (string key in charIndex.Keys)
    	{
    		if (!key.Equals(removeToken))
    		{
    			//Iterate the list of positions for this character and add them to the list
    			foreach (int index in charIndex[key])
    			{
    				charPositionList.Add(index, index);
    			}
    		}
    	}
    
    	StringBuilder sb = new StringBuilder();
    
    	//Build a string from the filtered list
    	foreach (int index in charPositionList.Keys)
    	{
            	sb.Append(text.Substring(charPositionList[index], 1));
    	}
    
    	return sb.ToString();
    }
    
    
  • (cs) in reply to Zeta Reticuli
    Zeta Reticuli:
    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

    Only the stupid ones.

    Seriously, reading compiler warnings is the only safe way to approach this problem, because the "make my code ugly by reversing conditionals" approach fails as soon as you compare variables: writing "if (b = a)" for "if (a == b)" is not going to help! So it's far better that people get used to being careful with = and ==, rather than relying on a "clever" syntactic crutch that will let them down silently and disastrously when they least expect it.

  • dan (unregistered) in reply to LizardKing
    LizardKing:
    Heres a dime, now get yourself a better compiler.
    Sometimes, in the real world you don't get to choose what compiler to use. In some cases you develop for a platform (maybe an embedded one) that is quite old and has a quite old toolchain, and then it's better to use simple tricks like having the constants on the left side in comparisons instead of hoping that the compiler will warn you. In other cases you inherit code that contains so many warnings already that it's a big chance that you'll miss the warnings concerning your change. But if you want to be an arrogant, then please go on, don't let me slow you down...

    Captcha: doom

  • Mario (unregistered) 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?
    VB.Net.

    String is a reference type, so ByVal means this function is getting a pointer, and may change the original string. This is one of the biggest mistakes in VB.Net(*) ... In conclusion, in the example, the string will have not have changed, and the return value is the new string.

    (*) Even with a "toy language", one needs to learn how to use it before attempting.

  • Zygo (unregistered) 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.

    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, ' ');

    Heinous, and also dead wrong. Assignment to *to++ must occur while to still points to the beginning of the string; otherwise, the function will preserve spaces when they appear at the beginning of the string.

  • Alyosha` (unregistered)

    Erlang!

    wtf(X) -> [I || I <- X, [I] /= " "].

    or, if you prefer ...

    wtf(X) -> lists:filter(fun(I) -> [I] /= " " end, X).

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

    Which will compile fine. On the other hand:

    Actually, any decent compiler will generate a warning, and not compile just fine.

    While it is mostly a style issue, it really grates on my to read code like that. We don't care what 3 is equal to, we want to know what a is equal to. Put a first, it reads better and makes more sense.

  • S|ic3 X (unregistered)

    The Real WTF is that the example in C places the literal values on the left side of the comparison operators and the variables on the right.

  • (cs) in reply to DrCode
    DrCode:
    JamesCurran:
    But, that bring us to another important point... What about tabs and other forms of whitespace? Has no one heard of isspace()?

    Congratulations, you've actually managed to turn what was merely a WTF into something that's actually broken.

    The original function only replaced spaces. With nothing else to go on (no documentation to the contrary, for example), we can only assume that it was MEANT to only replace spaces, and not tabs, carriage returns, line feeds, vertical tabs (!), or anything else. Your version changes the semantics of the function.

    Apparently the thinking here is, "Man, that is some messed up code, I could rewrite that to be a lot simpler, clearer, and more readable. Oh, and, also, that guy is only removing spaces, that must be because he didn't know how to handle tabs and other whitespace (I mean, just look, he could barely handle writing the version that just removes the spaces), so I'll help him out by changing it so that it removes all whitespace, not just spaces." WTF?

    This is true, which is why my Prolog version should actually be:

    is_not_space(Char):-		\+ char_code(' ',Char).
    despace(Spaced,Despaced):-	sublist(is_not_space,Spaced,X), string_to_list(Despaced,X).
    

    The previous version would strip all whitespace.

  • Jeff (unregistered)

    void removeSpace(char* string) { if( string ) *string = 0; }

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

Log In or post as a guest

Replying to comment #:

« Return to Article