Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace second occurence of ? with an &

Tags:

c#

regex

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

like image 212
stevepkr84 Avatar asked May 08 '14 16:05

stevepkr84


1 Answers

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);
like image 198
Selman Genç Avatar answered Nov 15 '22 06:11

Selman Genç