Thursday, December 26, 2024

CodeSOD: Spaced Out Replacement

Programming LanguageCodeSOD: Spaced Out Replacement


You have some text, and need to replace every sequence of spaces with a single space. E.g., My text becomes My text. Now, if you're most of us, you ignore the famous quote and reach straight for regexes.

But Samuel's co-worker isn't most of us.

toReturn = toReturn.Replace(" ", " ");
toReturn = toReturn.Replace("  ", " ").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ");

What I love about this is you can see the programmer gradually understanding the problem better, right here in the code.

Now, this is C#, where Replace replaces all occurences.

They start with one line: if there are two spaces, replace them with one. Oops, except, they can't count, and they actually write instructions to replace one space with one space.

Okay, that didn't work, let's try again. Let's replace two spaces with one space. Hey, that's got us partway there, but if, for example, we've got three or four spaces, this still leaves us with two spaces. Okay, let's just add another replace. Great, but oh wait, what if we have six spaces? The first replace knocks us down to three, the second to two, so we need a third one.

And so this developer kept adding Replace calls until the spaces got down to the count they expected. Here's hoping they never get a string with more contiguous spaces than this block can handle.

Then again, what's the worst that happens? They just need to add another Replace(" ", " "). Easy.

[Advertisement]
ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.

Check out our other content

Check out other tags:

Most Popular Articles