[Solved] Add one to C# reference number


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

2

solved Add one to C# reference number