C# 中的方法 return 给定字符的直接文本字符

Method in C# to return the immediate text character of a given character

如何在 c# 中实现 return 给定文本字符的直接文本字符的函数。字符应按字母顺序排列。 示例:给定字符 "C" 方法应该 return 字符 "D"。

char c = 'C';
char i = (char)(c + 1);
System.Diagnostics.Debug.WriteLine(i);

它将 'D' 输出到调试输出 window。

我想我找到了解决方案:

public static string GetNextLetter(string letter = null)
{
     if (IsStringNullOrEmpty(letter))
         return "A";

     char lastLetter = letter.Last();

     if (lastLetter.ToString() == "Z")
         return GetNextLetter(RemoveLastCharacter(letter)) + "A";
     else
         return RemoveLastCharacter(letter) + (char)(lastLetter + 1);
    }

欢迎大家提出更好的解决方案

这里有一个方法可以满足您的需求。但是没有检查非字母字符。

public static string ToNextAlpha(string str)
{
    if (str == null)
    {
        throw new ArgumentNullException("str");
        // Or you can just return "a";
    }

    var end = new StringBuilder();
    for (int index = str.Length - 1; index >= 0; index--)
    {
        char c = str[index];
        bool isZed = c == 'z' || c == 'Z';
        c = (char)(isZed ? c - 25 : c + 1);
        end.Insert(0, c);
        if (!isZed)
        {
            return str.Substring(0, index) + end;
        }
    }

    return "a" + end;
}

注意:这会将 "zz" 变为 "aaa",将 "ZZ" 变为 "aAA"。如果你想在前面加上一个大写 "A" 只需用你需要的任何逻辑更改最后一行。