I am being passed a string value that could begin with 0-4 decimal digits and ends with a small, but unknown, amount of non-decimal text. I need to pad the leading decimal digits out to four digits with the “0” character. If I am passed “abcd”, I would return “0000abcd”. If I passed “0xyz”, I would return “0000xyz”. And so on…
I am using the following code to detect how much padding I need to do:
int padding = 0;
int strlen = [rawString length];
NSRange rng = [rawString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
if (rng.length > 0 && rng.location < 4) // Characters were found at the end.
padding = 4 - rng.location;
else if (rng.length == 0 && strlen < 4) // Only numbers were found.
padding = 4 - strlen;
Now that I can accurately determine the padding my challenge is to add the padding in an efficient manner. I could do something like the following, but it just feels inefficient to me.
for (; padding > 0; padding--)
rawString = [@"0" stringByAppendingString:rawString];
Is there a better way to add a variable amount of padding to a string like the one I described?
EDIT: I considered chopping off the numerical portion, padding it, and then adding it back, but the number of corner cases seemed to indicate that an in situ solution would be best.
Since
paddingis between0and4, you could do this:The idea is to chop off the right number of zeros from a string containing four elements.