我的参考号是" DTS00001"它是C#程序中的String变量 我希望将此数字递增1,结果应该像" DTS00002"
这是我试过的代码,
while (reader.Read())
{
String str = reader["rfno"].ToString();
String st = str.Substring(3, 5);
int number = Convert.ToInt32(st);
number += 1;
string myNewString = "DTS" + number;
MessageBox.Show(myNewString);
结果在新号码之前不包含所需的前导零。
答案 0 :(得分:0)
是否做家庭作业,这是一种方法。由stemas answer影响严重。它使用Regex
将字母与数字分开。并PadLeft
保持正确的前导零数。
Tim Schmelters answer更优雅,但这也适用于其他类型的产品编号,并且不限于特定数量的前导零或特定字符集。这个解决方案的缺点是它必须[按字母顺序] [数字]。
private static string Increase(string productNo)
{
// This is a regex to split it into to groups.
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*[ _]?)(?<Numeric>[0-9]*)");
// Match the input string for the regex.
var match = numAlpha.Match(productNo);
// Get the alphabetical part.
var alpha = match.Groups["Alpha"].Value;
// Get the numeric part.
int num = int.Parse(match.Groups["Numeric"].Value);
// Add +1
num++;
// Combine the alphabetical part with the increased number, but use PadLeft to maintain the padding (leading zeros).
var newString = string.Format("{0}{1}", alpha, num.ToString().PadLeft(match.Groups["Numeric"].Value.Length, '0'));
return newString;
}
Console.WriteLine(Increase("DTS00008"));
Console.WriteLine(Increase("DTS00010"));
Console.WriteLine(Increase("DTS00020"));
Console.WriteLine(Increase("DTS00099"));
Console.WriteLine(Increase("PRODUCT0000009"));
Console.WriteLine(Increase("PRODUCT0000001"));
输出:
DTS00009
DTS00011
DTS00021
DTS00100
PRODUCT0000010
PRODUCT0000002