Anderson sends us a bit of C# code that does the simple job of removing multiple spaces, i.e. it converts “A    B” to “A B”. And, much to my surprise, I learned something about C# from reading this code.

private string RemoveDoubleSpaces(string strName)
{
    string newStrname = null;

    for (int i = 0; i < strName.Length; i++)
    {
        if (i > 0)
        {
            if ((strName[i] == Char.Parse(" ")) && (strName[i] == strName[i - 1]))
            {
                continue;
            }
            else
            {
                newStrname += strName[i].ToString();
            }
        }
        else
        {
            newStrname += strName[i].ToString();
        }
    }

    return newStrname;
}

There are some “interesting” choices here. Like using Char.Parse to convert the string " " into the character ' ', when they could have just used the character in the first place. Or the special case first step of the loop- a conditional that gets checked for every iteration when we know that it only executes the first time. We could easily move the initialization of newStrname outside of the loop and then just start the loop at 1, greatly simplifying the code.

But speaking of newStrname, this is where I learned something. At first glance, I assumed this code would just crash if it ever actually ran- newStrname is initialized to null, and then we call += on it- surely that doesn’t work on a null value? But it does.

And in retrospect, it makes sense: null + "some string" also works, and just does the sane behavior of returning "some string". In fact, the behavior is so obvious, that I now feel silly for thinking this worked any other way. Still, I was surprised that this code worked.

Speaking of code that works, Anderson threw all of this away and replaced it with the simpler return Regex.Replace(strName, @"s+", " ");, which isn’t doing exactly the same thing as the original code, but actually maps better to the requirement (the rule was that all whitespace should be replaced with a single space, not just space characters), so the code is simpler and a bug got fixed.

Remy Porter

Source link

You May Also Like

Delta Agent Calls For Dipshit Passengers To Mill About In Front Of Gate Before Their Turn To Board

CHICAGO—Speaking over the terminal’s intercom in preparation for an evening flight to…

Greg Abbot faces flat-tire frustration admist Texas Troubles

While another mass shooter was busy killing children and taking selfies, Greg…

Annoying Thing of The Day: People Who Do This In Stores

Here’s a great idea: when you go grocery shopping, just buy the…

Woman Born With Severe Birth Defects From Radiation Defied The Odds And Became An Olympic Champion

Do you remember that feeling when you had a performance at school?…