2016-11-24 61 views
-8

我的參考號是「DTS00001」這是在C#程序中的字符串變量
我想通過一個遞增這個數字和結果應該是像「DTS00002」添加一個C#參考號碼

這裏是我試過的代碼,

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); 

結果在新號碼前沒有包含所需的前導零。

+4

你嘗試過這麼遠嗎?可悲的是,我們不是您的個人代碼編寫服務。 – RandomStranger

+0

您可能會先分割Alpha數字和數字(使用'string.Substring()')。使用'int.TryParse()'解析數字。添加1並重新格式化 –

+3

它是作業... –

回答

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 
+0

$「{alpha} {num.ToString()。PadLeft(match.Groups [」Numeric「]。Value.Length,'0')}」;在這個代碼錯誤發生說;預計 – Yasitha

+0

@Yasitha - 改爲舊學校'string.Format'。 _string interpolation_可能有一些.NET版本的要求。 – smoksnes

+0

謝謝@smoksnes,它的工作,非常感謝你 – Yasitha