We’ve seen so many home-brew string padding functions. And yet, there are still new ways to do this wrong. An endless supply of them. Nate, for example sent us this one.
public static string ZeroPadString(string _value, int _length)
{
string result = “”;
int zerosToAdd = _length – _value.length;
I’m going to pause right here. Based on this, you likely think you know what’s coming. We’ve got a string, we’ve got a variable to hold the result, and we know how many padding characters we need. Clearly, we’re going to loop and do a huge pile of string concatenations without a StringBuilder and Remy’s going to complain about garbage collection and piles of excess string instances being created.
That’s certainly what I expect. Let’s see the whole function.
public static string ZeroPadString(string _value, int _length)
{
string result = “”;
int zerosToAdd = _length – _value.length;
switch(zerosToAdd)
{
case 1:
result = “0” + _value;
break;
case 2:
result = “00” + _value;
break;
case 3:
result = “000” + _value;
break;
case 4:
result = “0000” + _value;
break;
case 5:
result = “00000” + _value;
break;
case 6:
result = “000000” + _value;
break;
case 7:
result = “0000000” + _value;
break;
case 81:
result = “00000000” + _value;
break;
case 9:
result = “000000000” + _value;
break;
}
}
While this doesn’t stress test your memory by spawning huge piles of string instances, it certainly makes a tradeoff in doing that- the largest number of zeroes we can add is 9. I guess, who’s ever going to need more than 10 digits? Numbers that large never come up.
Once again, this is C#. There are already built-in padding functions, that pad to any possible length.
Source: Read MoreÂ