我想在C#windows应用程序中生成下一个字母数字字符串序列。检查最大数量并生成下一个序列
eg-
A10100001 => A10100002 => A10100003 => A10100004 ...... A10100999 => A10101001
ABC000001 => ABC000002 => ABC000003 => ABC000004 ...... ABC000999 => ABC001001
请帮助我,我是编程新手......
答案 0 :(得分:1)
尝试使用正则表达式来提取最后一个数字(我们必须增加):
private static string Next(string value) {
string number = Regex.Match(value, "[0-9]+$").Value;
return value.Substring(0, value.Length - number.Length) +
(long.Parse(number) + 1).ToString().PadLeft(number.Length, '0');
}
或Regex.Replace
版 terser ,但可读:
private static string Next(string value) {
return Regex.Replace(value, "[0-9]+$",
match => (long.Parse(match.Value) + 1).ToString($"D{match.Length}"));
}
测试:
// "abc0046"
Console.Write(Next("abc0045"));
// "abc0045xyz124" (please, notice, that it's the last 123 which is incremented)
Console.Write(Next("abc0045xyz123"));
如果你有一个序列项目相同模式,你可以使用 Linq :
string[] items = new string[] { "ABC001", "ABC105", "ABC024" };
// "ABC106"
Console.Write(Next(items.Max()));
答案 1 :(得分:0)