Increment a string with both letters and numbers

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

    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"
    

提交回复
热议问题