How do I replace a specific occurrence of a string in a string?

后端 未结 7 1561
野的像风
野的像风 2020-12-18 03:12

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

7条回答
  •  情深已故
    2020-12-18 03:57

    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.

提交回复
热议问题