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

前端 未结 3 1378
自闭症患者
自闭症患者 2020-12-22 03:12

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 g

3条回答
  •  我在风中等你
    2020-12-22 03:50

    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);
    }
    

提交回复
热议问题