The Daily WTF
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
To read the full article click on the 'post' link at the top.