您可以使用IndexOf指定开始索引来查找第二个问号的索引,然后使用Substring:
var index = input.IndexOf('?', input.IndexOf('?') + 1);
var ouput = string.Concat(input.Substring(0,index), "&", input.Substring(index + 1));
Run Code Online (Sandbox Code Playgroud)
或者:
var output = new string(input.Select((c, i) => i == index ? '&' : c).ToArray());
Run Code Online (Sandbox Code Playgroud)
您还可以编写扩展方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
var index = input.IndexOf('?', input.IndexOf('?') + 1);
var output = input.ReplaceWith('&', index);
Run Code Online (Sandbox Code Playgroud)