在字符串的末尾替换迭代器 [英] Replace iterator at the end of string

查看:233
本文介绍了在字符串的末尾替换迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关文件的功能,我添加了一个迭代器的文件的新名称。



该名称将是这样的:




  • 我的名字

  • 我的名字(1)

  • 我的名字(2)

  • ...

  • 我的名字(10)



为了寻找下一个可用号我用一个while循环:

 而(Stuff.FindNameByText(文本)= NULL)
{
文本=的String.Format({0}({1}),文字i.ToString());
I ++;
}
File.SetNewName(文本)



不过,当然这个代码给出我下面的输出:




  • 我的名字

  • 我的名字(1)

  • 我的名字(1)(2)

  • ...



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

 而(Stuff.FindNameByText(文本)!= NULL)
{
正则表达式的regex =新的正则表达式(的String.Format(\\ {0}。*?\\ {1},(,))) ;
文本= regex.IsMatch(文字,i.ToString());
File.SetNewName(文本)
}



也许有人可以帮助我一点点。如果迭代器在到底是不是存在 - 添加一个,否则取代现有的新号


解决方案

  VAR原稿=文本; 

,而(Stuff.FindNameByText(文本)!= NULL)
{
文本=的String.Format({0}({1}),原稿,我。的ToString());
I ++;
}
File.SetNewName(文本)


For a file function I added an iterator the the new name of the file.

The names will look like this:

  • My Name
  • My Name (1)
  • My Name (2)
  • ...
  • My Name (10)

For finding the next "available" number I'm using a while loop:

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

But this code of course gives me the following output:

  • My name
  • My name (1)
  • My name (1) (2)
  • ...

How do I first add an iterator the strings end (if not existing) - and otherwise replace the existing one. I did the following, but it would end in an infinite loop...

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

Maybe someone could help me out a bit. If iterator at the end is not existing - add one, otherwise replace existing one with new number.

解决方案

var orig = text;

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

这篇关于在字符串的末尾替换迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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