Comment On Removing Spaces, the Easy Way

There are tons of functions in so-called "standard" libraries, but sometimes the function you want just isn't there. Luckily, string functions are so simple to write that anyone can do it! [expand full text]
« PrevPage 1 | Page 2 | Page 3 | Page 4 | Page 5 | Page 6Next »

Re: Removing Spaces, the Easy Way

2007-02-22 09:09 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:11 • by Sebastián
Your implementation is not C++, is plain C.

Re: Removing Spaces, the Easy Way

2007-02-22 09:12 • by Stiggy (unregistered)
Apart from anything else, putting the required code in the Else section....

The've not heard of NOT then.

Re: Removing Spaces, the Easy Way

2007-02-22 09:12 • by jms (unregistered)
Looks like the original code was in VB.NET... How about the following?

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




Re: Removing Spaces, the Easy Way

2007-02-22 09:12 • by Not telling you... (unregistered)
How about:

new_string = edit$(old_string,2%)

in VAX/DEC BASIC...

Re: Removing Spaces, the Easy Way

2007-02-22 09:13 • by 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?

Re: Removing Spaces, the Easy Way

2007-02-22 09:16 • by Ade (unregistered)
121897 in reply to 121896
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

Re: Removing Spaces, the Easy Way

2007-02-22 09:16 • by CrystalMethod (unregistered)
121898 in reply to 121892
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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:17 • by Doug (unregistered)
I'd add :

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

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

Re: Removing Spaces, the Easy Way

2007-02-22 09:17 • by mav (unregistered)
121900 in reply to 121892
Sebastián:
Your implementation is not C++, is plain C.


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

Re: Removing Spaces, the Easy Way

2007-02-22 09:19 • by mav (unregistered)
121901 in reply to 121892
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

Re: Removing Spaces, the Easy Way

2007-02-22 09:20 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:25 • by Anonymous (unregistered)
My version:

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

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

Re: Removing Spaces, the Easy Way

2007-02-22 09:29 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:32 • by NateP (unregistered)
121906 in reply to 121896
"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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:34 • by sir_flexalot
121907 in reply to 121893
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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:36 • by Robin Barker (unregistered)
perl: sub removeSpaces { $_[0] =~ s/ //g; }

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

Re: Removing Spaces, the Easy Way

2007-02-22 09:36 • by cfreeman (unregistered)
Perl:

$str =~ s/ //g;

Some things Perl was just meant to do.

Re: Removing Spaces, the Easy Way

2007-02-22 09:37 • by hmmmm... (unregistered)
121910 in reply to 121896
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. ;-)

Re: Removing Spaces, the Easy Way

2007-02-22 09:39 • by WIldpeaks
121911 in reply to 121896
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...

Re: Removing Spaces, the Easy Way

2007-02-22 09:39 • by 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>

Re: Removing Spaces, the Easy Way

2007-02-22 09:40 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:47 • by G-Unit
121914 in reply to 121906
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"

Re: Removing Spaces, the Easy Way

2007-02-22 09:48 • by 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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:51 • by Guy (unregistered)
121916 in reply to 121896
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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:51 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:52 • by 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?!

Re: Removing Spaces, the Easy Way

2007-02-22 09:53 • by lf (unregistered)
121919 in reply to 121908
Why use a regex? $foo =~ tr/ //d is much faster

Re: Removing Spaces, the Easy Way

2007-02-22 09:54 • by rbowes
121920 in reply to 121898
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.

Re: Removing Spaces, the Easy Way

2007-02-22 09:55 • by Anonymous (unregistered)
void RemoveSpaces(char* str)

{
char* to = str;
while(*str) {
if (*str != ' ')
*to++ = *str;
str++;
}
*to = 0;
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:56 • by 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 ]]
}

Re: Removing Spaces, the Easy Way

2007-02-22 09:57 • by Jared (unregistered)
121923 in reply to 121915
C++ string replace functions:

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

Re: Removing Spaces, the Easy Way

2007-02-22 09:58 • by aikii
121924 in reply to 121898
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!(" ","")

Re: Removing Spaces, the Easy Way

2007-02-22 10:01 • by jpvlsmv (unregistered)
121925 in reply to 121903
Your code still has a bug in it. Here's the fixed version:

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

Re: Removing Spaces, the Easy Way

2007-02-22 10:03 • by treefrog
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);
}

Re: Removing Spaces, the Easy Way

2007-02-22 10:03 • by 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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 10:05 • by 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....)

Re: Removing Spaces, the Easy Way

2007-02-22 10:06 • by Coolvibe (unregistered)
121930 in reply to 121929
Uhm, I of course mean
stripchar(somestring, ' ');
. :P

Re: Removing Spaces, the Easy Way

2007-02-22 10:07 • by Sebastián
121931 in reply to 121901
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.

Re: Removing Spaces, the Easy Way

2007-02-22 10:08 • by LizardKing
121932 in reply to 121920
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.

Re: Removing Spaces, the Easy Way

2007-02-22 10:08 • by Otto
121933 in reply to 121926
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;
}

Re: Removing Spaces, the Easy Way

2007-02-22 10:11 • by grumble (unregistered)
121934 in reply to 121920
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)

Re: Removing Spaces, the Easy Way

2007-02-22 10:11 • by 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, ' ');

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;
}


Re: Removing Spaces, the Easy Way

2007-02-22 10:14 • by Sebastián
121936 in reply to 121935
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.

Haskell

2007-02-22 10:15 • by meak (unregistered)
removeSpaces = filter (' ' /=)

Re: Removing Spaces, the Easy Way

2007-02-22 10:15 • by Tchakkazulu (unregistered)
Some Haskell:

removeSpaces = filter (/= ' ')

Re: Removing Spaces, the Easy Way

2007-02-22 10:15 • by XIU
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.

Re: Removing Spaces, the Easy Way

2007-02-22 10:19 • by 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

Re: Removing Spaces, the Easy Way

2007-02-22 10:19 • by cracki (unregistered)
121941 in reply to 121927
also:
char *removespaces(char *s)

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

Re: Removing Spaces, the Easy Way

2007-02-22 10:19 • by 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));
}
« PrevPage 1 | Page 2 | Page 3 | Page 4 | Page 5 | Page 6Next »

Add Comment