Could anyone please provide the appropriate code to replace the second instance only of "?" in a string with a "&" ?
I've looked around but can't seem this done, and I'm not too hot with regex to begin with.
Thanks
You can use IndexOf
specifying the start index to find index of second question mark and then use 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());
You can also write an extension method:
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);
}
Then use it:
var index = input.IndexOf('?', input.IndexOf('?') + 1);
var output = input.ReplaceWith('&', index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With