如何在C#中拆分混合字符串

时间:2019-11-13 15:17:37

标签: c#

这里是样本输入和输出。 我有如下字符串。 我想将字符串的最后一位数字加1

AVAP001P001输出AVAP001P002

CD009输出CD010

1 个答案:

答案 0 :(得分:2)

这是您可以使用的快速解决方案。您可能想使其更加健壮,但我继续并添加了适用的注释来描述正在做的事情。

static void Main(string[] args)
{
    var s = "CBC004DS009";

    // get the very last index of the character that is not a number
    var lastNonNumeric = s.LastOrDefault(c => !char.IsDigit(c)); 
    if (lastNonNumeric != '\x0000')
    {
        var numericStart = s.LastIndexOf(lastNonNumeric);

        // grab the number chunk from the string based on the last character found
        var numericValueString = s.Substring(numericStart + 1, s.Length - numericStart - 1);

        // convert that number so we can increment accordingly
        if (int.TryParse(numericValueString, out var newValue))
        {
            newValue += 1;

            // create the new string without the number chunk at the end
            var newString = s.Substring(0, s.Length - numericValueString.Length);

            // append the newly increment number to the end of the string, and pad
            // accordingly based on the original number scheme
            newString += newValue.ToString().PadLeft(numericValueString.Length, '0');

            Console.WriteLine(newString);
        }
    }
}