[英]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". 我想将其增加到“ SD50MRF1000”而不是“ 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" 但是结果是:它隔离了“ SD”和“ 50MRF1000”
I would use LINQ for this purposes usually: 我通常将LINQ用于此目的:
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"
结果=>“ SD50MRF1000”
Just don't forget to add this to your using directives: 只是不要忘记将其添加到您的using指令:
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. 像@ S.Akbari一样,我认为Linq在这里可以很好。 This snippet will work on string like
"SD50MRF50"
. 该代码段将适用于
"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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.