How to search and replace exact matching strings only

c#

Solution

You can use Regex to do this:

Extension method example:

public static class StringExtensions
{
    public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
    {
        string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
        return Regex.Replace(input, textToFind, replace);
    }
}

Usage:

  string text = "Add Additional String to text box";
  string result = text.SafeReplace("Add", "Insert", true);

result: "Insert Additional String to text box"

Problem

I need to search in a string and replace a certain string Ex: Search String "Add Additional String to text box". Replace "Add" with "Insert" Output expected = "Insert Additional String to text box" If you use string s="Add Additional String to text box".replace("Add","Insert"); Output result = "Insert Insertitional String to text box" Have anyone got ideas to get this working to give the expected output? Thank you!

Original source

Related problems