简体   繁体   中英

How to increment the last part of string that contains a number

I have this serial :

string serialTXT = "SD50MRF999";

I want to increase it to "SD50MRF1000" not "SD51MRF000".

I tried this :

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));

But the result : it isolate "SD" and "50MRF1000"

I would use LINQ for this purposes usually:

string serialTXT = "SD50MRF01";
string intPart = string.Join("", serialTXT.Reverse().TakeWhile(char.IsDigit).Reverse());
int intP = int.Parse(intPart);
serialTXT = serialTXT.Remove(serialTXT.Length - intPart.Length) + 
            (intP < 10 ? "0" + (intP + 1) : (intP + 1).ToString());

Result => "SD50MRF1000"

Just don't forget to add this to your using directives:

using System.Linq;

You can use a regex to get the last digits, then convert those to a number, and tack it onto the end of the part of the string which didn't match:

string serialTXT = "SD50MRF999";
Regex re = new Regex( "([0-9]+)$"); /* digits at the end */
string end = re.Match(serialTXT).Value;
int newNum = int.Parse(end) + 1; /* we need a number to increment it */
string newSerial = serialTXT.Substring(0, serialTXT.Length - end.Length) + newNum;

非常规表达式的答案是检查字符串中的最后一个字符以查看它是否是一个数字,然后检查下一个,以此类推,直到获得您的数字为止。

Like @S.Akbari, I think Linq can be nice here. This snippet will work on string like "SD50MRF50" .

public static void Main()
{
    var str = "SD50MRF999";
    var digits = str.Reverse().TakeWhile(char.IsDigit);
    var number = digits.Select((x,i) => (x - '0') * Math.Pow(10, i)).Sum();
    var letters = str.Remove(str.Length - digits.Count());

    // use letters + (++number).ToString("00")
    // or letters + (++number).ToString("D2")
    // to write `01`, `02`, `03` etc.
    Console.WriteLine(letters + (++number));
}

Try it Online!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM