gpt4 book ai didi

c# - 替换字符串末尾的迭代器

转载 作者:行者123 更新时间:2023-11-30 21:11:59 25 4
gpt4 key购买 nike

对于文件函数,我添加了一个文件新名称的迭代器。

名称将如下所示:

  • 我的名字
  • 我的名字 (1)
  • 我的名字 (2)
  • ...
  • 我的名字 (10)

为了找到下一个“可用”号码,我使用了一个 while 循环:

while (Stuff.FindNameByText(text) != null)
{
text = string.Format("{0} ({1})", text, i.ToString());
i++;
}
File.SetNewName(text)

但是这段代码当然会给我以下输出:

  • 我的名字
  • 我的名字 (1)
  • 我的名字 (1) (2)
  • ...

我如何首先在字符串末尾添加一个迭代器(如果不存在) - 否则替换现有的迭代器。我做了以下操作,但它会以无限循环结束......

while (Stuff.FindNameByText(text) != null)
{
Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", "(", ")"));
text = regex.IsMatch(text, i.ToString());
File.SetNewName(text)
}

也许有人可以帮我一下。如果末尾的迭代器不存在 - 添加一个,否则用新数字替换现有的迭代器。

最佳答案

var orig = text;

while (Stuff.FindNameByText(text) != null)
{
text = string.Format("{0} ({1})", orig, i.ToString());
i++;
}
File.SetNewName(text)

关于c# - 替换字符串末尾的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7769928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com