问题描述
string rev = "Value";
char C1 = char.Parse(rev);
c1++;
但是 rev 字符串的值不以 Z 结尾,而是上升到最后一个值 AZ。 (如 excel 列仅供参考)。 因此,上面的代码不适用于 AA、AB 等值,并且不会增加它。 如果我将 rev 值设为“AA”,我不确定如何找到下一个值。有人可以指导吗。
解决方法
这是一个简单的方法,虽然可能有点冗长或昂贵。
它期望输入格式正确,如果它不只包含字母 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 上查看。