递增包含字母和数字的字符串 [英] Increment a string with both letters and numbers

查看:55
本文介绍了递增包含字母和数字的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,需要加1.该字符串同时包含字符和数字值.

I have a string which i need to increment by 1 The string has both characters and numeric values.

我的字符串布局如下"MD00494"

The string layout i have is as follows "MD00494"

我如何将其增加到"MD00496"?"MD00497"等

How would i increment this to "MD00496" & "MD00497" ect

如果它是带有数字的普通字符串,我会将其解析为一个整数.

If it was a normal string with numbers i would parse it to an int.

我尝试了以下

 int i = int.Parse(sdesptchNo);
 i++;
 txtDispatchNo.Text = i.ToString();

任何人都知道我将如何处理这个问题.

Anyone any ideas how i would go about this.

推荐答案

您首先应该弄清楚字符串之间的任何共性.如果末尾总有一个字母前缀,后跟数字(宽度固定),那么您只需删除字母,解析其余的字母,递增,然后再次粘贴在一起即可.

You first should figure out any commonality between the strings. If there is always a prefix of letters followed by digits (with a fixed width) at the end, then you can just remove the letters, parse the rest, increment, and stick them together again.

例如在您的情况下,您可以使用以下内容:

E.g. in your case you could use something like the following:

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

另一个可能更健壮的选项是

Another option that might be a little more robust might be

var newString = Regex.Replace(x, "\\d+",
    m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));

这将用相同宽度的递增数字替换字符串中的任何数字,但将每个非数字都完全相同并放置在同一位置.

This would replace any number in the string by the incremented number in the same width – but leaves every non-number exactly the same and in the same place.

这篇关于递增包含字母和数字的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆