- 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
I've actually done this on an occasion or two:
But if we MUST do it iteratively
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!)
Admin
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.
Admin
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.
Admin
Well, it IS very much different in C++. In C++, you would use std::string and iterators, not raw char * pointers.
Admin
Which are useless in this case. I would use Boost.Regex or Boost.String_algo.
Admin
Maybe it is just me, but this seems awfully trivial...
Isn't it?
IMEANSRSLYGUYS.
Admin
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.
Admin
Admin
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(" ", "")
Admin
Admin
This all would have been much more interesting if the task was instead to remove all EXTRA spaces, leaving only single spaces, if any.
Admin
Obviously:
Plug and pray...
Admin
in perl: $var ~= s/\s+ / /g;
Admin
Nope, VB6 did have a method called 'Replace' which does exactly what we want it to.
Admin
Haskell version:
removeSpaces = filter ' '
Admin
Haskell version:
removeSpaces = filter (==' ')
Admin
This will fail for strings with two or more consecutive spaces. Thankfully, this is easy to fix with a helper function:
Admin
tr/ //d;
Admin
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.
Admin
... I'm confused. How is a compiler that can assign the value of 'a' to the integer '3' BETTER than one that will refuse?
Admin
Admin
I really hope thats <sarcasm>, can't see how anyone could could miss the overflow exception when i = strFldName.Length
Admin
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.
Admin
Since we're publishing our own implementations, here's mine.
Q&D, with comments for you HLL programming n00bs
Admin
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.
Admin
You mean VB5. Replace was added in VB6 (and I remember being very happy at the time due to that new feature).
Admin
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))) ))
Admin
IF sentence has space THEN remove space THANKS
Admin
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...
Admin
IMO, this version is clearer than most others, because the only statement that's not completely boilerplate is the line
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.
Admin
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.
Admin
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
Admin
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);
Admin
euh .. obviously
Function RemoveWhiteSpace(text as String) as String If text = Null Then Return Null Return text.Replace(" ", "") End Function
captcha: scooter
Admin
Admin
(overcoming surprise that there is another VAX/DEC/Compaq/HP/Alpha/Integrity(*) BASIC programmer reading this site!)
(*) delete where appropriate
Admin
DKO has got the right idea for C++. It's as simple as
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.
Admin
Admin
Javascript can be used for good. Please don't mock a perfectly acceptable language just because it is abused by script kiddies.
Admin
My version
Admin
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...
If anyone's interested in seeing some examples of how this is used I'd be happy to provide. >:)
Admin
But legibility is presumably not one of those things. O.o
Captcha: Mmmm waffles.
Admin
// 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.
Admin
OK, I will start writing some object oriented class including some design patterns for this task...
Admin
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.
Admin
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.
create a copy of the string to be altered (incase there is a problem!
create a var that can be used later.
pass the copied string text, character by character through a function that looks for " " and strips it out of the temporary var.
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!
Admin
Admin
Actually VB6 DOES have Replace
Admin
newstr = ''.join(oldstr.split('+'))
Admin
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:
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.