I have a string which may contain \"title1\" twice in it.
e.g.
server/api/shows?title1=its always sunny in philadelphia&title1=breaking ba
Here is a C# extension method I created for a similar task that may come in handy.
internal static class ExtensionClass
{
public static string ReplaceNthOccurance(this string obj, string find, string replace, int nthOccurance)
{
if (nthOccurance > 0)
{
MatchCollection matchCollection = Regex.Matches(obj, Regex.Escape(find));
if (matchCollection.Count >= nthOccurance)
{
Match match = matchCollection[nthOccurance - 1];
return obj.Remove(match.Index, match.Length).Insert(match.Index, replace);
}
}
return obj;
}
}
Then you can use it with the following example.
"computer, user, workstation, description".ReplaceNthOccurance(",", ", and", 3)
Which will produce the following.
"computer, user, workstation, and description"
OR
"computer, user, workstation, description".ReplaceNthOccurance(",", " or", 1).ReplaceNthOccurance(",", " and", 2)
Will produce the below.
"computer or user, workstation and description"
I hope this helps someone else who had the same question.