Last night I was practicing incrementing strings. What it needs to do is increment the last character if it is a digit or letter. Special characters are ignored.
The code that I have written does the job but I have a feeling it can be accomplished in a more elegant way. Or a faster way.
Can somebody suggest faster, easier, more elegant approaches.
Below the code I have written:
public static string Increment(this String str)
{
var charArray = str.ToCharArray();
for(int i = charArray.Length - 1; i >= 0; i--)
{
if (Char.IsDigit(charArray[i]))
{
if(charArray[i] == '9')
{
charArray[i] = '0';
continue;
}
charArray[i]++;
break;
}
else if(Char.IsLetter(charArray[i]))
{
if(charArray[i] == 'z')
{
charArray[i] = 'a';
continue;
}
else if(charArray[i] == 'Z')
{
charArray[i] = 'A';
continue;
}
charArray[i]++;
break;
}
}
return new string(charArray);
}
999andZZZcorrectly. I would have expected1000andAAAA. but it shouldn't be too hard to fix =) \$\endgroup\$