替换第二次出现的 ? 带着 &

ste*_*r84 5 c# regex

任何人都可以提供适当的代码来仅替换“?”的第二个实例。在带有“&”的字符串中?

我环顾四周,但似乎无法完成,而且一开始我对正则表达式并不太感冒。

谢谢

Sel*_*enç 7

您可以使用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)