2 回答

TA貢獻1828條經驗 獲得超3個贊
讓我們實現GetNextValue方法:對于給定 value的(例如"A9999"),我們計算下一個("B0001"):
private static string GetNextValue(string value) {
StringBuilder sb = new StringBuilder(value);
// Digits only: 1239 -> 1240
for (int i = value.Length - 1; i >= 0; --i) {
if (sb[i] < '9') {
sb[i] = (char)(sb[i] + 1);
return sb.ToString();
}
else if (sb[i] >= 'A')
break;
else
sb[i] = '0';
}
// 1st letter: 9999 -> A001
if (sb[0] == '0') {
sb[0] = 'A';
if (sb[sb.Length - 1] == '0')
sb[sb.Length - 1] = '1';
return sb.ToString();
}
// Leading letters AZ999 -> BA001
for (int i = value.Length - 1; i >= 0; --i) {
if (sb[i] >= 'A') {
if (sb[i] < 'Z') {
sb[i] = (char)(sb[i] + 1);
if (sb[sb.Length - 1] == '0')
sb[sb.Length - 1] = '1';
return sb.ToString();
}
else
sb[i] = 'A';
}
}
// All letters increment: ABCDZ -> ABCEA
for (int i = 0; i < value.Length; ++i) {
if (sb[i] == '0') {
sb[i] = 'A';
if (sb[sb.Length - 1] == '0')
sb[sb.Length - 1] = '1';
return sb.ToString();
}
}
// Exhausting: ZZZZZ -> 00000
return new string('0', value.Length);
}
如果要枚舉這些值:
private static IEnumerable<string> Generator(int length = 5) {
string item = new string('0', length);
do {
yield return item;
item = GetNextValue(item);
}
while (!item.All(c => c == '0'));
}
演示:(讓我們使用一個長度字符串3)
Console.Write(string.Join(Environment.NewLine, Generator(3)));
結果:(項目27234總數;18769482項目如果length == 5)
000
001
002
...
009
010
...
999
A01
...
A99
B01
...
Z99
AA1
...
AA9
AB1
...
AZ9
BA1
...
ZZ9
AAA
AAB
AAC
...
AAZ
ABA
...
ZZY
ZZZ

TA貢獻1810條經驗 獲得超4個贊
這是一個擴展方法,它將整數值格式化為您的格式(帶前導字母):
public static string ToZormat(this int value, int length = 5)
{
string map = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] result = new char[length];
var x = value;
for(int i = 0; i < length; i++)
{
int threshold = (int)Math.Pow(10, length - i - 1);
var index = Math.Min(map.Length - 1, x / threshold);
result[i] = map[index];
x -= threshold * index;
}
return new String(result);
}
當您將數字格式化為長度為 5 的字符串時,前導字母會出現在 value 99,999、 next go A0,000、 ...A9,999等之后B0,000。如您所見,第一個字符會更改每個10,000數字。第二個字符改變每個1,000數字。最后,每個數字的第五個字符都會改變。我們只需要實現那個算法。
基本步驟:
定義格式中使用的字符映射
計算當前位置 (i) 的字符變化閾值 - 它將是 10 的冪:10,000, 1,000, 100, 10, 1。
從地圖中獲取字符索引。它只是適合該值的閾值數,但不超過地圖中的字符數。
計算輸入值的剩余部分并轉到下一個位置
您應該為適合格式化字符串的給定長度的最大值添加驗證。
長度 3 的樣本:
Enumerable.Range(0, 3886).Select(x => x.ToZormat(3))
輸出:
000
001
002
...
999
A00
A01
...
A99
B00
B01
...
Z99
ZA0
ZA1
...
ZZ9
ZZA
...
ZZZ
- 2 回答
- 0 關注
- 188 瀏覽
添加回答
舉報