Increment a string with both letters and numbers

前端 未结 8 1803
故里飘歌
故里飘歌 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:18

    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);
    
    0 讨论(0)
  • 2020-12-19 01:21

    Here's my solution:

    string str = Console.ReadLine();
    string digits = new string(str.Where(char.IsDigit).ToArray());
    string letters = new string(str.Where(char.IsLetter).ToArray());
    string newStr;
    int number;
    
    if (!int.TryParse(digits, out number)) 
    {
      Console.WriteLine("Something weird happened");
    }
    if (digits.StartsWith("0"))
    {
      newStr = letters + (++number).ToString("D5");
    }
    else
    {
      newStr = letters + (++number).ToString();
    }
    

    Try it!

    0 讨论(0)
提交回复
热议问题