我需要编写一个方法,通过循环旋转将字符串值从 AAA 递增到 ZZZ(ZZZ 之后的下一个值是 AAA)
这是我的代码:
public static string IncrementValue(string value) {
if (string.IsNullOrEmpty(value) || value.Length != 3) {
string msg = string.Format("Incorrect value ('{0}' is not between AAA and ZZZ)", value);
throw new ApplicationException(msg);
}
if (value == "ZZZ") {
return "AAA";
}
char pos1 = value[0];
char pos2 = value[1];
char pos3 = value[2];
bool incrementPos2 = false;
bool incrementPos1 = false;
if (pos3 == 'Z') {
pos3 = 'A';
incrementPos2 = true;
} else {
pos3++;
}
if (incrementPos2 && pos2 == 'Z') {
pos2 = 'A';
incrementPos1 = true;
} else {
if (incrementPos2) {
if (pos2 == 'Z') {
pos2 = 'A';
incrementPos1 = true;
}
pos2++;
}
}
if (incrementPos1) {
pos1++;
}
return pos1.ToString() + pos2.ToString() + pos3.ToString();
}
我知道这段代码很脏而且效率不高,但我不知道如何正确地完成它。
如何保护此代码段? (这只会在 windows 平台上运行)
如何优化它并使其更具可读性?
感谢您的意见
最佳答案
从数学角度考虑:您的字符串(AAA、AAB、...)的行为就像自然数(000、001、...),只是基数为 26 而不是基数 10。
因此,您可以使用相同的原理。这是一些代码:
// iterate cyclicly from 0 to 26^3 - 1
int incrementValue(int i) {
// a verbose way of writing "return (i + 1) % 26^3"
i++;
if (i == 26*26*26) i = 0;
return i;
}
// convert 0 to AAA, 1 to AAB, ...
string formatValue(int i) {
var result = new StringBuilder();
result.Insert(0, (char)('A' + (i % 26)));
i /= 26;
result.Insert(0, (char)('A' + (i % 26)));
i /= 26;
result.Insert(0, (char)('A' + (i % 26)));
return result.ToString();
}
关于c# - 通过循环旋转将值从 AAA 递增到 ZZZ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047119/