任何人都可以提供适当的代码来仅替换“?”的第二个实例吗?在带有“&”的字符串中?
我环顾四周,但似乎无法做到这一点,而且我一开始对正则表达式不太热衷。
Thanks
您可以使用IndexOf
指定起始索引来查找第二个问号的索引,然后使用Substring
:
var index = input.IndexOf('?', input.IndexOf('?') + 1);
var ouput = string.Concat(input.Substring(0,index), "&", input.Substring(index + 1));
Or:
var output = new string(input.Select((c, i) => i == index ? '&' : c).ToArray());
您还可以编写扩展方法:
public static string ReplaceWith(
this string source,
char charToReplace,
int index)
{
if(source == null) throw new ArgumentNullException("source");
if (index == -1) return source;
var output = new char[source.Length];
for (int i = 0; i < source.Length; i++)
{
if (i != index) output[i] = source[i];
else output[i] = charToReplace;
}
return new string(output);
}
然后使用它:
var index = input.IndexOf('?', input.IndexOf('?') + 1);
var output = input.ReplaceWith('&', index);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)