Increment a string with both letters and numbers

You need to find the position of the first digit in the string. Then split the string into 2 fields.

0 1 2 3 4 5 6

M D 0 0 4 9 4

The first field will be the non numeric part "MD" The second field will be the numeric part "00494"

Increment the numeric only part to "00495"

You will lose the leading zero's so you'll need to pad your new number with the same amount of zero's once you've incremented.

Then join the 2 fields.


Assuming that you only need to increment the numeric portion of the string, and that the structure of the strings is always - bunch of non-numeric characters followed by a bunch of numerals, you can use a regular expression to break up the string into these two components, convert the numeric portion to an integer, increment and then concatenate back.

var match = Regex.Match("MD123", @"^([^0-9]+)([0-9]+)$");
var num = int.Parse(match.Groups[2].Value);

var after = match.Groups[1].Value + (num + 1);

You first should figure out any commonality between the strings. If there is always a prefix of letters followed by digits (with a fixed width) at the end, then you can just remove the letters, parse the rest, increment, and stick them together again.

E.g. in your case you could use something like the following:

var prefix = Regex.Match(sdesptchNo, "^\\D+").Value;
var number = Regex.Replace(sdesptchNo, "^\\D+", "");
var i = int.Parse(number) + 1;
var newString = prefix + i.ToString(new string('0', number.Length));

Another option that might be a little more robust might be

var newString = Regex.Replace(x, "\\d+",
    m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));

This would replace any number in the string by the incremented number in the same width – but leaves every non-number exactly the same and in the same place.


Here is one Non-Regex way :P

string str = "MD00494";
string digits = new string(str.Where(char.IsDigit).ToArray());
string letters = new string(str.Where(char.IsLetter).ToArray());

int number;
if (!int.TryParse(digits, out number)) //int.Parse would do the job since only digits are selected
{
    Console.WriteLine("Something weired happened");
}

string newStr = letters + (++number).ToString("D5");

output would be:

newStr = "MD00495"

Tags:

C#

.Net