加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通过字符串迭代?

发布时间:2020-12-15 20:48:35 所属栏目:百科 来源:网络整理
导读:不完全确定这是可能的,但是说我有两个这样的字符串: "IAmAString-00001""IAmAString-00023" 通过向上移动最终数字的索引,从IAmAString-0001迭代到IAmAString-00023会有什么快速的方法? 问题比这更普遍,例如我可以处理的字符串可以是任何格式,但最后一串字
不完全确定这是可能的,但是说我有两个这样的字符串:

"IAmAString-00001"
"IAmAString-00023"

通过向上移动最终数字的索引,从IAmAString-0001迭代到IAmAString-00023会有什么快速的方法?

问题比这更普遍,例如我可以处理的字符串可以是任何格式,但最后一串字符将始终是数字,所以类似于Super_Confusing-String#w00t0003,在这种情况下,最后的0003将是是我用来迭代的东西.

有任何想法吗?

解决方法

string start = "IAmAString-00001";
string end = "IAmAString-00023";

// match constant part and ending digits
var matchstart = Regex.Match(start,@"^(.*?)(d+)$");
int numberstart = int.Parse(matchstart.Groups[2].Value);

var matchend = Regex.Match(end,@"^(.*?)(d+)$");
int numberend = int.Parse(matchend.Groups[2].Value);

// constant parts must be the same
if (matchstart.Groups[1].Value != matchend.Groups[1].Value)
    throw new ArgumentException("");

// create a format string with same number of digits as original
string format = new string('0',matchstart.Groups[2].Length);

for (int ii = numberstart; ii <= numberend; ++ii)
    Console.WriteLine(matchstart.Groups[1].Value + ii.ToString(format));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读