Increment a string with both letters and numbers

前端 未结 8 1828
故里飘歌
故里飘歌 2020-12-19 00:50

I have a string which i need to increment by 1 The string has both characters and numeric values.

The string layout i have is as follows \"MD00494\"

How woul

8条回答
  •  执念已碎
    2020-12-19 01:05

    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.

提交回复
热议问题