【问题标题】:How to find out next character alphabetically till ZZ [closed]如何按字母顺序找出下一个字符直到 ZZ [关闭]
【发布时间】:2021-07-15 15:42:18
【问题描述】:

我正在使用以下代码来查找下一个字母。

    string rev = "Value";
char C1 = char.Parse(rev);
c1++;

但是 rev 字符串的值不以 Z 结尾,它上升到最后一个值 AZ。 (如excel列仅供参考)。 因此,上面的代码不适用于 AA、AB 等值,也不会增加它。 如果我将 rev 值设为“AA”,我不确定如何找到下一个值。谁能指导一下。

【问题讨论】:

  • this 对您有帮助吗?它是字母数字,所以不完全是你要问的,但似乎逻辑适用
  • 你能把规则定义的更​​清楚吗?给我们一些输入和预期输出。 “AA”->“BA”? “ZA”->“AZA”?等
  • 你能举一个输入和预期输出的例子吗?
  • @sinatr 输入可以是任何内容,请参见以下示例。例如 1. 输入 c 我期望的输出是 D。但是当我的输入是 Z 时输出应该是 AA,这就像一个 excel 列名。当输入为 AB 时,输出应为 AC。

标签: c# next alphabet


【解决方案1】:

这是一种简单明了的方法,虽然可能有点冗长或昂贵。

它期望输入格式正确,如果不只包含字母 A-Z,则会抛出异常。

public static string Increment(string input)
{
    List<char> chars = input.ToList();
    
    // Loop over the characters in the string, backwards
    for (int i = chars.Count - 1; i >= 0; i--)
    {
        if (chars[i] < 'A' || chars[i] > 'Z')
        {
            throw new ArgumentException("Input must contain only A-Z", nameof(input));
        }
        
        // Increment this character
        chars[i]++;
        
        if (chars[i] > 'Z')
        {
            // Oops, we overflowed past Z. Set it back to A, and ...
            chars[i] = 'A';
            
            // ... if this is the first character in the string, add a 'A' preceeding it
            if (i == 0)
            {
                chars.Add('A');
            }
            // ... otherwise we'll continue looping, and increment the next character on
            // the next loop iteration
        }
        else
        {
            // If we didn't overflow, we're done. Stop looping.
            break;  
        }
    }
    
    return string.Concat(chars);
}

测试用例:

A -> B
B -> C
Z -> AA
AA -> AB
AB -> AC
AZ -> BA
BC -> BD
ZZ -> AAA

dotnetfiddle 上查看。

【讨论】:

  • 给定的样本Value也包括小写字母
  • @fubo 确实,这就是为什么我预先声明并包含测试用例的原因。如果我们得到一些澄清,我会删除/编辑:我发现有时获得反馈的最简单方法是在提问者面前放一些东西,让他们说如果/为什么错了!
  • @canton7 您提供的上述代码对我有用。感谢您的回复。
  • @sayyad 如果这解决了您的问题,请考虑将其标记为接受答案(并支持它)
猜你喜欢
  • 2010-11-04
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多