Yasitha Yasitha - 15 days ago 12
C# Question

Add one to C# reference number

My reference number is "DTS00001" it is a String variable in C# program

i want to increment this number by one and the result should be like "DTS00002"

here is the code i tried,

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


The result doesn't contain the required leading zeros before the new number.

.

Answer

Homework or not, here's one way to do it. It's heavily influensed by stemas answer. It uses Regex to split the alphabetical from the numeric. And PadLeft to maintain the right number of leading zeroes.

Tim Schmelters answer is much more elegant, but this will work for other types of product-numbers as well, and is not limited to a specific number of leading zeros or a specific character set in the beginning. The downside with this solution is that it has to be [alphabetical][numerical].

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

Output:

DTS00009
DTS00011
DTS00021
DTS00100
PRODUCT0000010
PRODUCT0000002