如何在c#中生成字母数字序列号

时间:2017-07-27 18:23:00

标签: c# c#-4.0

我在下面写了代码来生成我的8位数字符号,增量应该从左到右。

假设我的起始编号是ABC00001,下一个增量编号将是ABC00002

数字将增加到9,在9之后它将变为A. 例如:ABC00009 - > ABC00000A - > ABC00000B - > .... - > ABC00000Z

在Z之后

它将最后的第二位数字改为ABC0000A1 - > ABC0000A2 ......

 public static string GeneratedNextevcPrimakryKey()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string str = string.Empty;

            var maxNumber = "ONC0BJKZ";

            string splitnumber = maxNumber.Substring(3, 5);
            char[] temp = splitnumber.ToCharArray();
            //find last index number/character
            for (int i = splitnumber.Length - 1; i >= 0; i--)
            {
                if (char.IsNumber(splitnumber[i]))
                {
                    int fifthvalue = Convert.ToInt32(splitnumber[i].ToString());

                    //increment 5th digit character
                    if (fifthvalue == 9)
                    {
                        temp[i] = 'A';
                        break;
                    }
                    else
                    {
                        fifthvalue = fifthvalue + 1;
                        string f = Convert.ToString(fifthvalue);
                        temp[i] = Convert.ToChar(f);
                        //sb.Append(fifthvalue);
                        break;
                    }
                }
                else
                {
                    char letter = splitnumber[i];
                    char nextChar = new char();
                    if (letter == 'z')
                    {
                        string strvalue = Convert.ToString(1);
                        temp[i] = Convert.ToChar(strvalue);
                    }
                    else if (letter == 'Z')
                    {
                        //last digit character
                        string strvalue = Convert.ToString(1);
                        temp[i] = Convert.ToChar(strvalue);
                        str = new string(temp);

                        break;
                    }
                    else

                        nextChar = (char)(((int)letter) + 1);

                    temp[i] = nextChar;
                    str = new string(temp);
                    break;
                }


            }
            return str;
        }

1 个答案:

答案 0 :(得分:1)

您可以尝试实施Base36

void Main()
{
    // 17 would be the number you want to convert to your ABC format
    var result = ToBase36(17);
    Console.WriteLine(result);
    // Will print "ABC00000H"
}

private static string ToBase36(ulong value)
{
    const string base36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var sb = new StringBuilder(9);
    do
    {
       sb.Insert(0, base36[(byte)(value % 36)]);
       value /= 36;
    } while (value != 0);

    var paddedString = "ABC" + sb.ToString().PadLeft(6, '0');
    return paddedString;
}