Search code examples
c#stringincrementuppercaselowercase

Increment a string from numbers 0-9 to lowercase a-z to uppercase A-Z in C#


I want to be able to have a string 6 characters long starting with '000000'. Then I want to increment it by one '000001' when I hit 9 I want to go to '00000a' when I get to z I want to go to '00000A'. When 'Z' is reached I want to reset the first to 0 and start with the next position '000010' So on and so forth. '000011','000012'...'0000a0','0000a1'...'0000A0','0000A1'

How would I do this in C#?

Thank you in advance. Mike


Solution

  • This uses the IntToString supporting arbitrary bases from the question Quickest way to convert a base 10 number to any base in .NET?, but hardcoded to use your format (which is base 62).

    private static readonly char[] baseChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
    private const long targetBase = 62;
    private const long maxNum = 62L*62*62*62*62*62 - 1;
    public static string NumberToString(long value)
    {
        if (value > maxNum)
            throw new ArgumentException();
        char[] result = "000000".ToCharArray();
    
        int i = result.Length - 1;
        do
        {
            result[i--] = baseChars[value % targetBase];
            value /= targetBase;
        } 
        while (value > 0);
    
        return new string(result);
    }