Comment On Classics Week: Removing Spaces, the Easy Way

Removing Spaces, the Easy Way was originally published on February 22, 2007. [expand full text]
« PrevPage 1 | Page 2Next »

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:03 • by akatherder
One of these days, a programming language will include some sort of replace() function.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:09 • by Kiasyn
thats still not c++ ;-;

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:10 • by Keith Hackney (unregistered)
fist!

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:15 • by Keith Hackney (unregistered)
dup!

Everyone knows the best way to remove spaces is to take a screenshot of the string, print it out, physically cut the spaces out using a scalpel, reassemble the rest of the string, place it on a wooden table, take a photo of it and then scan in the photo.

The Real WTF is that they didn't use PHP and XML.

CAPTCHA = comb-over

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:30 • by GuntherVB
136018 in reply to 136016
Keith Hackney:
The Real WTF is that they didn't use PHP and XML.


Have they tried javascript?

captcha: Why use anything when you have javascript..

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:35 • by Anonymous (unregistered)
136024 in reply to 136011
you mean like in C# or Java

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:36 • by Anonymous (unregistered)
136025 in reply to 136011
you mean like in C# or Java

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:44 • by Jimmy (unregistered)
136026 in reply to 136016
Keith Hackney:
dup!

Everyone knows the best way to remove spaces is to take a screenshot of the string, print it out, physically cut the spaces out using a scalpel, reassemble the rest of the string, place it on a wooden table, take a photo of it and then scan in the photo.

The Real WTF is that they didn't use PHP and XML.

CAPTCHA = comb-over


No, the Real WTF is that they didn't use J#.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:46 • by sir_flexalot
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 09:54 • by Tepid Perl User (unregistered)
136029 in reply to 136011
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?

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:01 • by Magus (unregistered)
136031 in reply to 136028
sir_flexalot:
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!


That's assuming your test that one string equals another string with space removed works correctly. You could make an error, such as testing that the two strings are equal ignoring spaces.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:04 • by Ted (unregistered)
my version:

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

char *to = str;
char *from = str;

do{
if( *str != ' ' ) *to++ = *str;
while( *str++ != '\0 );

return str;
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:09 • by Skurry
Thank god this is very easy and straightforward in Java:

public String removeSpaces(String paula) {
String willy = "";
StringTokenizer george = new StringTokenizer(paula, " ");
while(george.hasMoreTokens()) {
willy = new String(willy.toString() + george.nextToken().toString();
}
return paula.replaceAll(" ", "")
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:13 • by C.M (unregistered)
I was called in to fix an old Excel add-in written in VBA. It's the worst code I've ever seen...

Example: Two functions used everywhere in the code to change change " " to "_" or the other way around.

Function Change_toBlankforText(txt As String) As String
Dim n As Integer
Dim retur As String
retur = ""
For n = 1 To Len(txt)
If Mid(txt, n, 1) <> "_" Then
retur = retur & Mid(txt, n, 1)
Else
retur = retur & " "
End If
Next n
Change_toBlankforText = retur
End Function

Function ChangeBlankto_forText(txt As String) As String
Dim n As Integer
Dim retur As String
retur = ""
For n = 1 To Len(txt)
If Mid(txt, n, 1) <> " " Then
retur = retur & Mid(txt, n, 1)
Else
retur = retur & "_"
End If
Next n
ChangeBlankto_forText = retur
End Function

I chose to replace it with this instead:
Replace(txt, " ", "_")

There's enough WTF's in this add-in to fill a whole month of submissions.
/C.M

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:14 • by Sandpit (unregistered)
Use a real language such as VB6:

Replace(myString, " ", "")

(Captcha= ewww)

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:30 • by SomeCoder (unregistered)
The STL C++ way:

string str = "I have spaces to remove";
string newStr = "";
newStr.resize(str.length());
remove_copy_if(str.begin(), str.end(), newStr.begin(), bind2nd(equal_to<char>(), ' '));

// newStr == "Ihavespacestoremove"


There's probably some other ways using the STL too.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:31 • by Poltras (unregistered)
Here's another unit-tested version (which works, although might not should... or whatever)... Please note the C standard lib notations.

// String Remove Spaces. Isnt that obvious?
void strrms( char *p )
char *s=(char*)calloc(strlen(p)*sizeof(char),1);
char *c=strtok(p," ");
while(c) strcat(s,c), c=strtok(0," ");
strcpy(p,s);
}

BTW, I think there is a better (read shorter and more obscure) way to make the while loop, but I don't have much time.

captcha: darwin. Give some of those to the ppl who write here without knowing what they talk about.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:38 • by ForcedSterilizationsForAll (unregistered)
136039 in reply to 136028
sir_flexalot:
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!


That only works if you then compare the two strings character by character, making sure to take the case into account.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:44 • by TekdOut (unregistered)
136040 in reply to 136028
with the a little help from a quantum computer...this solutuion would take no time at all

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:45 • by misha
136041 in reply to 136028
sir_flexalot:
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!


How do you then generate thestringwithoutspaces for the comparision in the termination condition? There must be a neat recursive solution here...

sub strip_spaces {
my $s = shift;

my $r;
while ($r = generate_random_string() ne strip_spaces($s)) {};
return $r;
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:52 • by Sgt. Preston (unregistered)
136043 in reply to 136035
Sandpit:
Use a real language such as VB6:

Replace(myString, " ", ""))

Or use another real language such as VB.NET (in which our WTF is written):

myString = myString.Replace(" ","")

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:52 • by Nomikos (unregistered)
136044 in reply to 136036
I think I like the Haskell way better:
removeSpaces = filter (/= ' ')

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 10:55 • by Sgt. Preston (unregistered)
Casting my mind all the way back to February 22nd has me feeling all nostalgic. We should have Classics Week at least once a month.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 11:06 • by Monkey (unregistered)
136050 in reply to 136037
Not shorter but more obscure?

char *removespaces(char *str)
{
char *p_from = str, *p_to = str;
while(*p_to) *p_to++ = *(p_from += (*p_from == ' ') ? 1: 0), p_from++;
return str;
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 11:31 • by CynicalTyler (unregistered)
I still prefer feeding my spaces to demonic forces to get rid of them...

http://worsethanfailure.com/Comments/Removing_Spaces,_the_Easy_Way.aspx?pg=2#121986

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 11:42 • by AJ (unregistered)
The source for this version is longer than both the WTF "reference" and Monkey's version (and unlike Ted's version it actually compiles), but g++ generates fewer machine instructions for it:

char* rmSpaces(char* str) {

if (str) {
char* to = str;
char* from = str;
char ch;

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

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 11:48 • by Peter Lawrey (unregistered)
Or in Java

myString = myString.replaceAll(" +", "");
// to remove white space.
myString = myString.replaceAll("\\s+", "");

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 12:01 • by D (unregistered)
136071 in reply to 136050
Monkey:
Not shorter but more obscure?

char *removespaces(char *str)
{
char *p_from = str, *p_to = str;
while(*p_to) *p_to++ = *(p_from += (*p_from == ' ') ? 1: 0), p_from++;
return str;
}


Would that even work? What does the following return?

removespaces("this  has  multiple     spaces    in   a row");

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 12:15 • by java.lang.Chris;
How about designing functions that don't restrict you to removing or replacing just one character?

#include <stdio.h>


static char *strremove(char *, char);
static char *strreplace(char *, char, char);

int
main(int argc, char *argv[])
{
char rem[] = " I have spaces to remove ";
char rep[] = " I have spaces to replace ";

printf("'%s'\n", strremove(rem, ' '));
printf("'%s'\n", strreplace(rep, ' ', '_'));

return 0;
}

char *
strremove(char *str, char c)
{
char *to, *from;

if (str) {
for (to = from = str; *from; ++from)
if (*from != c)
*to++ = *from;
*to = '\0';
}

return str;
}

char *
strreplace(char *str, char o, char n)
{
char *to, *from;

if (str) {
for (to = from = str; *from; ++from)
if (*from != o)
*to++ = *from;
else
*to++ = n;
*to = '\0';
}

return str;
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 12:16 • by Reaver (unregistered)
136074 in reply to 136033
Skurry:
Thank god this is very easy and straightforward in Java:

public String removeSpaces(String paula) {
String willy = "";
StringTokenizer george = new StringTokenizer(paula, " ");
while(george.hasMoreTokens()) {
willy = new String(willy.toString() + george.nextToken().toString();
}
return paula.replaceAll(" ", "")
}


Typical.

While Willy and George are dicking around with their 'tokens', Paula is getting the job done on her own.

Bet the guys try and take the credit as well...

;->

Cheers,
Reaver

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 12:42 • by Random832
void removespaces(char *target, char *src) {
if(*src && *src++ != ' ') *target++ = src[-1];
if(*src) removespaces(target,src);
}

elegantly bizarre.

Addendum (2007-05-11 12:50):
oops. forgot "else*target=0". also, the "*src &&" in the first condition is not strictly necessary

void removespaces(char*target,char*src){if(*src++!=' ')*target++=src[-1];if(*src)removespaces(target,src);else*target=0;}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 12:44 • by FlyboyFred (unregistered)
136082 in reply to 136036
SomeCoder:
The STL C++ way:

string str = "I have spaces to remove";
string newStr = "";
newStr.resize(str.length());
remove_copy_if(str.begin(), str.end(), newStr.begin(), bind2nd(equal_to<char>(), ' '));

// newStr == "Ihavespacestoremove"


There's probably some other ways using the STL too.


Much easier:

string str = "I have spaces to remove";
str.erase(remove(str.begin(), str.end(), ' '), str.end());

Or for char arrays:

char* removeSpaces(char* buf)
{
int len = strlen(buf);
std::remove(buf, buf+len+1, ' ');
return buf;
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 14:08 • by dp.design
void vacuum(std::string &s) {

for (int x = 0; x < s.length(); x++)
if (isspace(s[x]))
s.erase(x, 1);
}

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 14:09 • by Robert (unregistered)
I am so glad I know PHP and can do this so much better in it. If only they would come up with some sort of str_replace() function though... Oh well.

<?php

function rs($s)
{
if ($s == '') return;
if ($s == ' ') return '';
$r = ' ';
$sl = strlen($s);
$st = '';
for ($i = 0; $i < $sl; ++$i)
{
if ($s[$i] == $r)
{
$s[$i] = '';
}

$st .= $s[$i];
}

return $st;
}
?>


CAPTCHA: howdy
RESPONSE: Fine, and you?

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 14:09 • by jtwine
> I don't even know what the hell the Try/Catch is supposed
> to be doing

Well, in most languages string operations like MID/Substring cause the allocation of a new string, hence memory allocation, which can fail raising an exception... :P

Seriously, this is one of the things most quickly forgotten by C++ MFC developers that do know how CString objects really work.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 14:14 • by jtwine
136111 in reply to 136013
Kiasyn:
thats still not c++ ;-;

Not sure if you are serious or not because of the strange kinda-sorta-smiley, but it really is C++...

This line:

for ( char* from = str ; '\0' != *from ; ++from )

-Will not compile in plain C.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 14:48 • by Random832
136114 in reply to 136111
Assuming it's followed by a statement or a block, why not?

Or are you still using the c89 standard? That's so... 1989.

incidentally, "'\0' !=" is a no-op.

for(char *from=str;*from;++from) { ... }

perfectly valid c99.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 15:17 • by Claudiu Saftoiu (unregistered)
Python way is a one-liner! Probably for other scripting languages too:

>>> string = "hey i want to remove spaces? kk"
>>> removed = "".join(c for c in string if c != ' ')
>>> removed
'heyiwanttoremovespaces?kk'

or alternatively:
>>> filter(lambda x: x!=' ', string)
'heyiwanttoremovespaces?kk'

or a faster but even stranger looking way
>>> filter(' '.__ne__, string)
'heyiwanttoremovespaces?kk'

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 16:03 • by duuuuuude (unregistered)
Everyone say it with me now...

"Regular Expressions Are Your Friends!"

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 17:20 • by dp.design
Dammit, in both occurrences of this article, I posted my vacuum method, and not once has anyone commented how clever my name for it was. :(

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 17:28 • by DWalker59
136145 in reply to 136028
sir_flexalot:
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!


Wort sorting algorithm ever: Generate all possible permuations of the input, and return the one that is sorted.

OR, keep randomly generating permutations of the input, and return when the one you hit on, happens to be sorted.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 17:58 • by Aurélien (unregistered)
136147 in reply to 136121
Or even simpler:
removed = string.replace(" ", "")

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 20:01 • by Claudiu Saftoiu (unregistered)
136156 in reply to 136147
Lol. Yeah, I guess that would be the fastest, simplest way. Silly me.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 20:45 • by -M- (unregistered)
136157 in reply to 136121
Or...you could do it like real python..
string = 'hey i want to remove spaces? kk'
string = string.replace(' ','')

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-11 22:42 • by Claudiu Saftoiu (unregistered)
136162 in reply to 136157
in my goal of finding a quick one-line way to do it, i forgot str had a replace function. I promise, my python code is better than that usually!

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-12 02:48 • by kupal (unregistered)
the real wtf is that he should've used regular expression to find the space then have an character array that stores the non-space characters then converting it to a string when finished parsing.

captcha: putanginamo

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-12 16:09 • by SuperBlah (unregistered)
136185 in reply to 136037
Don't try to use this in a multithreaded application if you're using strtok. Also, 'more obscure' does not equal 'better'.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-12 16:14 • by Joseph Newton (unregistered)
136186 in reply to 136073
java.lang.Chris;:
How about designing functions that don't restrict you to removing or replacing just one character?

#include <stdio.h>


static char *strremove(char *, char);
static char *strreplace(char *, char, char);

int
main(int argc, char *argv[])
{
char rem[] = " I have spaces to remove ";
char rep[] = " I have spaces to replace ";

printf("'%s'\n", strremove(rem, ' '));
printf("'%s'\n", strreplace(rep, ' ', '_'));

return 0;
}

char *
strremove(char *str, char c)
{
char *to, *from;

if (str) {
for (to = from = str; *from; ++from)
if (*from != c)
*to++ = *from;
*to = '\0';
}

return str;
}

char *
strreplace(char *str, char o, char n)
{
char *to, *from;

if (str) {
for (to = from = str; *from; ++from)
if (*from != o)
*to++ = *from;
else
*to++ = n;
*to = '\0';
}

return str;
}


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.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-12 18:11 • by ehird (unregistered)
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.

Re: Classics Week: Removing Spaces, the Easy Way

2007-05-13 02:50 • by Matthew (unregistered)
136194 in reply to 136028
sir_flexalot:
I like generating random strings until you get one that's the same as your starting string but without the spaces. Takes a long time, but eventually it will work perfectly!


Hey, it's O(1)!

Or would that be O(rand(1))?

-matthew
« PrevPage 1 | Page 2Next »

Add Comment