Search code examples
c#stringintegerformat

How to determine the format of an integer , increment it , and return it in the same format based on the input?


My question is similar to this question How to increment a number but keep formatting except the format is not known beforehand and is determined by the input integer.

So if I enter 0001, it will return 0002, if I enter 01, it will return 02, if I enter 1, it will return 2.

I know for known formats like 0001 I can convert it ToString("000"), but I don't know how to get the format of the any input integer and apply it back after the increment.


Solution

  • Seems like you are working with strings which can be incremented using the following method.

    public class Helpers
    {
        public static string NextValue(string sender)
        {
            string value = Regex.Match(sender, "[0-9]+$").Value;
            return sender[..^value.Length] + (long.Parse(value) + 1)
                .ToString().PadLeft(value.Length, '0');
        }
    }
    

    Sample usage

    string[] values = new[] {"0001", "01", "A001" };
    
    foreach (var value in values)
    {
        Debug.WriteLine($"{value,-10}{Helpers.NextValue(value)}");
    }
    

    Results

    0001      0002
    01        02
    A001      A002