Iterating through the Alphabet - C# a-caz

后端 未结 10 1090
無奈伤痛
無奈伤痛 2020-11-29 03:03

I have a question about iterate through the Alphabet. I would like to have a loop that begins with \"a\" and ends with \"z\". After that, the loop begins \"aa\" and count to

10条回答
  •  悲哀的现实
    2020-11-29 03:36

    Edit: Made it do exactly as the OP's latest edit wants

    This is the simplest solution, and tested:

    static void Main(string[] args)
    {
        Console.WriteLine(GetNextBase26("a"));
        Console.WriteLine(GetNextBase26("bnc"));
    }
    
    private static string GetNextBase26(string a)
    {
        return Base26Sequence().SkipWhile(x => x != a).Skip(1).First();
    }
    
    private static IEnumerable Base26Sequence()
    {
        long i = 0L;
        while (true)
            yield return Base26Encode(i++);
    }
    
    private static char[] base26Chars = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
    private static string Base26Encode(Int64 value)
    {
        string returnValue = null;
        do
        {
            returnValue = base26Chars[value % 26] + returnValue;
            value /= 26;
        } while (value-- != 0);
        return returnValue;
    }
    

提交回复
热议问题