Translate

Home > December 2020

December 2020

Char Increment Autogenerate Max Value

Tuesday, December 8, 2020 Category : 0

 This method take a string as input and it sequentially increment like excel header


 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetMax("BAA"));
            Console.ReadLine();
        }

        private static string GetMax(string maxvalue)
        {
            int minAsci = 65;
            int maxAsci = 90;

            int len = maxvalue.Length;

            int[] charAscii = new int[len];
            for (int i = 0; i < len; i++)
            {
                charAscii[i] = (int) maxvalue[i];
            }

            bool needChangePrevious = false;
            for (int i = len; i > 0; i--)
            {
                if (i == len)
                {
                    if (charAscii[i-1] < maxAsci)
                    {
                        charAscii[i-1]++;
                    }
                    else
                    {
                        charAscii[i-1] = minAsci;
                        needChangePrevious = true;
                    }
                }
                else
                {
                    if (needChangePrevious)
                    {
                        if (charAscii[i-1] < maxAsci)
                        {
                            charAscii[i-1]++;
                            needChangePrevious = false;
                        }
                        else
                        {
                            charAscii[i-1] = minAsci;
                            needChangePrevious = true;
                        }
                    }
                }
            }

            string newMax = "";
            if (maxvalue == "")
            {
                newMax = "A";
            }
            else if (needChangePrevious == false)
            {
                for (int i = 0; i < len; i++)
                {
                   newMax += (char)charAscii[i] ;
                }
            }
            else if (needChangePrevious == true)
            {
                newMax = "A";
                for (int i = 0; i < len; i++)
                {
                    newMax += (char)charAscii[i];
                }
            }

            return newMax;
        }
    }

Powered by Blogger.