- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
ok, but you lose a point because you don't handle multiple spaces.
static void remove_spaces (char s) { charp,*q;for (p=q=s; *p; *p != ' ' ? *q++ = *p++ : *p++);*q='\0'; }
This was my ternary operator version.
Admin
If Not strFldNm is nothing then [blabla] Else return string.empty End If
No overhead of exceptions here, and nothing with spaces removed is an empty string.
Admin
Until some damn fool writes:
if ((a = b) == TRUE)
then the whole thing falls flat on its face.
Really, C++ only has a fixed set of about 30 operators, even if you count the duplicate union/binary operators like * and -. Yes you can redefine the behavior of some of them sometimes, but in C++ you can't make up new operators on the fly like "@!$" or "<<<", so your investment in memorizing the full set will pay off until the next revision of the ISO standard, probably even longer since they don't add new operators on every revision.
It can't be that hard for people to finally learn what all the operators they use in C++ actually mean, so they can use assignment when they mean assignment and equality when they mean equality. If you can count parentheses and deference operators you can bloody well count equal signs too. There's no excuse for people who get confused and write
when they obviously meant
Now try maintaining code written in a language which ships with 100+ operators for built-in types and allows users to define more at runtime--as in 'I think I'll define operator #$%@^@$!^$++ in this function...'
Admin
A try block with an empty catch block in a string manipulating function is "reasonably efficient"?
Admin
Okay, I really couldn't resist my previous proposition.
So here is the link to the parallel AJAX implementation of removewhitespaces
iswhitespace.php just returns nothing if the parameter is a space, or else echoes the string provided. For extra fun I added random sleep to the php ... erm I mean extra heavy parallel processing to check if it's really a whitespace, to emulate real-life enterprisey conditions.
Admin
Scanned through four pages, and at a brief glance it seems I have the tightest one yet:
void despace_in_place(char* s) { char* o = s; for(o = s; *s; s++) if(*s != ' ') *o++ = *s; *o = 0; }
Admin
Admin
That's exactly what happens. The WOPR tries to get the secret launch codes for the nuclear missiles by removing whitespaces from the bible. I love that scene of war games when he finds one digit at a time ! Well, brute force has to be photogenic.
Admin
One addition, a more interesting way to do this in VB.Net...
Admin
Just write:
if (const_cast<const A &>(a) = b)
This will work regardless of compiler warning settings, although it fails if somebody defines bool A::operator=(foo) const.
Admin
[quote user="Zygo"]
Apparently there's no excuse for people who get extra )'s when they cut and paste either.
Admin
I vote for autoconverted from legacy VB. We have coverted some old code from VB6 and it looked a bit like that in VB.net. Most of it has since been converted to the correct dotNET-ish way of doing things (using the standard library, OOP, try/catch vs. on error goto, etc.), but one can still find some gems like this hidden away in svn.
Admin
Tcl one, boring:
string map {{ } {}} $str
Michael
Admin
Then there's Perl: D:\my_path>perl -e "($line = 'line with spaces') =~ s/ //g; print $line;" linewithspaces
..and that is in a DOS prompt, a less-than-friendly environment for perl -e
[Captcha [and hang]: dubya -- what's good for Saddam...]
Admin
Which languages can you be ignorant of and still be considered to have atleast half a brain? ;-)
Admin
With 4 pages of responses, am I the only one so far to note that the VB function in the article only removes spaces in a very weird sense?
How could the author have not noticed this, and if they did, why would they possibly need that string of spaces? I've needed to count spaces before, but never extract them out into their own string.
Admin
/me cries from holding back fits of laughter in the cubicle farm
Admin
Or in VMS DCL:
new_line = f$edit(line, "COMPRESS")
Admin
Maybe it's just me, but the original function doesn't look like it does what we all think it does.
It seems to be putting each space in RemoveSpaces, but not removing them from the original string in any way. Ie, if your incoming string was "hi there, sir", at the end of the function the string would remain intact and RemoveSpaces would be " ". Am I missing something? (I don't do any VB, so maybe I am)
Admin
/usr/bin/tr -d " "
Captcha: SevereAnalBleeding
Admin
If you really want to do it in place to a C style string in C++, the following one liner should work:
std::remove(s, s + strlen(s) + 1, ' ');
Admin
calling that function string_filter would cost you 3 characters but would have improved the readability of your code enormously.
Admin
Not quite there, eh..
Check the line closely: If (x[i] == " ") Then Else y = y & x[i] Endif
There's an "Else" in there - this terminates the "when the character is a space" condition and goes to the "when the character is not a space" condition.
Admin
int foo(char *in, char *out) { return (*out = *in) && foo(++in, (*in)^' '?++out:out); }
returns 0 on success.
Obfuscation and recursion, what more could one possibly want?!
Admin
Perhaps, but it isn't just string_filter.. It's filter_n_characters_of_string. And nobody wants to type that whole thing out. So what would you do? string_n_filter? Equally meaningless. Go with strnfilter - at least that's a common usage in C (what with strncpy and strncat and etc..).
Admin
Oho! I was hoping someone would post it in Prolog! But what will the interpreter do if I call despace(_, "Thisisastring!" ). I bet it goes crazy trying to find every combination. ;)
Admin
... apparently (and it isn't just you, I've noticed at least 5 others) people don't understand that using programs on a command line to solve this problem is not actually solving the problem.
The programmer has designed the function to remove spaces from strings in memory. While it's possible that he only uses the function on files that he reads into memory, it's more likely that he's using it for different purposes.
But if you want to go ahead and start up a whole new process just so you can eliminate spaces from your in-core strings, go right ahead. ..wtf.
Admin
In Delphi:
...which should be bloated enough for anyone.
-Harrow.
Admin
Assuming the rule for "not a space" is first, you'd most likely get the same string.
Admin
Are you going to release this under GPL? I'd love to have this in my PowerString library. I'm slowly replacing all the Microsoft 'string' bits with my own. First I replaced their rubbish immutable 'string' struct with my own 'string' class ... you can modify any char without having to create a new object. I can't believe Microsoft made such a basic mistake with the framework ...
Admin
Admin
I'm thinking that "bloated" would look more like ...
def remove_spaces(x): is_space = [] no_spaces = ""
Which .. of course .. is exactly the same as:
remove_spaces = lambda x: filter(lambda y: y != " ",x)
(..and slightly worse than remove_spaces = lambda x: "".join(x.split(" "))..)
Hmm.. I should consider starting a paid-by-the-line code-refactorer job..
Admin
From the original article:
char* RemoveSpaces( char *str ) { if ( NULL == str ) return NULL;
}
This "reference" implementation is also sub-optimal. Depending on the input string, it can actually work slower than the "WTF" version. Especially when there is no space to remove; in that case, the "WTF" version simple does one strchr (supposedly highly-optimzed) which returns NULL, while the "better" version copies the whole string over itself. Can we call that premature optimization?
Here is how it should be:
char* RemoveSpaces( char *str ) { if ( NULL == str ) return NULL;
}
Admin
REM Windows batch file implementation @echo off setlocal set spaceless= :loop if "%1empty"=="empty" goto :end set spaceless=%spaceless%%1 shift goto :loop :end echo %spaceless% endlocal
Admin
I'm a bit bothered by how many people still think byte-wise string manipulation (esp. in C) is the way to go. With UNICODE, characters can be one, two, three even four bytes. Please get away from ASCII string maniupulation. It's just not cool anymore :)
Admin
Admin
[code] cobain:$ cat test.c
int main() { int a = 0; if (a=1) printf("foo\n"); }
cobain:$ cc test.c
cobain:$ cc -Wall test.c
test.c: In function
main': test.c:4: warning: suggest parentheses around assignment used as truth value test.c:5: warning: implicit declaration of function
printf' test.c:6: warning: control reaches end of non-void function [\code]Anyone who claims that if(a = 3) {...} could be problematic clearly doesn't no their way around a compiler. Despite using Wall for anything I've coded, I don't recall ever having seen this warning for my own code - is it really such a problem?
C4PTCH4: fukkoff
PS: my initals are G.R.G, but I'm not the grg from the other WTF.
Admin
x86 assembler (32-bit MASM):
; Accepts a pointer to a null-terminated string in ESI ; as input, buffer in EDI for output removeSpaces PROC PUSHA
DoRemove: CMP [esi], 0 JE FinishedRemove CMP [esi], ' ' JE DontCopy MOVSB JMP DoRemove DontCopy: INC esi JMP DoRemove
FinishedRemove: MOVSB ; move null byte POPA RET
removeSpaces ENDP
Not very well optimized, I'm afraid. I was trying to work out a way to use one of the REP instructions, but I'm not sure how, since you have to check for two equalities. You could calculate the string length first and use that in ECX, but then you'd have to use SCASB to find the spaces and do all sorts of value juggling to copy them properly with MOVSB, since that doesn't change flags. Either way, this is probably much faster than any algorithm presented so far except maybe some of the C ones.
Not an option in interpreted languages. Python doesn't allow assignment in conditions at all, and I hear Perl doesn't with use strict, but PHP has no protection whatsoever. Not even a runtime notice.Admin
No, it IS C++ because in plain C one cannot declare variables anywhere inside a block, as Derrick did for "to"
Admin
Hmm, this is true. I just didn't expect anyone to actually continue with C's terrible naming conventions. ;-)
Anyway, I'm happy with string_filter unless you are going to provide a function to work on the entire string as well as this one.
(filter_string is also a better name than string_filter :-)
Admin
The fastest way to do many string manipulations in AppleScript is to split the string into a list based on some delimiter character (using the global AppleScript property "AppleScript's text item delimiters") and then join that list back into a string using different delimiters. So:
on remove_spaces(s) set AppleScript's text item delimiters to " " set s to text items of s -- makes list of space-delimited substrings of s set AppleScript's text item delimiters to "" set s to s as Unicode text -- rejoins list into string with empty delimiters return s end remove_spaces
remove_spaces("This is a test") --> Thisisatest
Admin
The Catch block is for when there is at least one space removed and the index will go out of bounds.
xsl does a lot of things badly, but others very well. String functions are not so hot, but I think you could get rid of a space with translate.
Admin
// C
void remove_char(char *str, char c) { if(!str) return;
char itr = str - 1; while((++itr = *str++)) if(*itr == c) itr--; }
// ML
fun remove_char c xs : char list = let fun rc ( nil) = nil | rc (x::xs) = if x = c then rc(xs) else x::rc(xs) in rc xs end;
Admin
Being readable, however, just ain't one of them.
Admin
The indentation didn't show up on my code: that was not intentional.
Admin
inspect(string," ","");
Admin
3 void removeS(char* str) { 4 int off = 0; 5 while(*str++ != NULL) { 6 if((*str = *(str + off)) == ' ') { 8 str--; 9 off++; 10 } 11 } 12 }
haha, that was kinda fun
Admin
damn bbcode. Anyway, pretty happy with that
Admin
Time to get really mean :D
O(N) complexity, which is as good as it gets. For whoever said the original function is quicker earlier.. you're an idiot, how do you think strchr SEARCHES for that space? The search is O(N) to begin with.
Admin
Neat, but "bet&&you++can't&&handle++this!"