15

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!

Darshana
  • 564
  • 1
  • 4
  • 13

6 Answers6

25

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"

sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • 2
    This solution doesnt work if I need to replace a word that starts with @. Fiddle here https://dotnetfiddle.net/9kgW4h How can I get this working in this scenario. – Frenz Jan 16 '17 at 05:46
  • It works for me. However, I have added a Regex.Escape() on the string to find otherwise it will not work if the string to find have a special char in it like '(1)'. string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", Regex.Escape(find)) : find; – Arnab May 23 '21 at 15:51
5
string pattern = @"\bAdd\b";
string input = "Add Additional String to text box";
string result = Regex.Replace(input, pattern, "Insert", RegexOptions.None);  

"\bAdd\b" ensures that it will match the "Add" which is not part of other words. Hope it's helpful.

Xiaodan Mao
  • 1,648
  • 2
  • 17
  • 30
4

answer for:
"This solution doesnt work if I need to replace a word that starts with @. Fiddle here dotnetfiddle.net/9kgW4h How can I get this working in this scenario. – Frenz Jan 16 '17 at 5:46"

possible solution:

public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) {
    string searchString = find.StartsWith("@") ? $@"@\b{find.Substring(1)}\b" : $@"\b{find}\b"; 
    string textToFind = matchWholeWord ? searchString : find;
    return Regex.Replace(input, textToFind, replace);
} 
1
//Find and Replace A word in c#
public static class Program
    {
        public static string Replace(this String str, char[] chars, string replacement)
        {
            StringBuilder output = new StringBuilder(str.Length);
            bool replace = false;
            if (chars.Length - 1 < 1)
            {
                for (int i = 0; i < str.Length; i++)
                {

                    char c = str[i];
                    replace = false;
                    //  int val = Regex.Matches(ch.ToString(), @"[a-zA-Z]").Count;


                    for (int j = 0; j < chars.Length; j++)
                    {
                        if (chars[j] == c)
                        {
                            replace = true;

                            break;

                        }

                    }

                    if (replace)
                        output.Append(replacement);
                    else
                        output.Append(c);
                }
            }
            else
            {

                int j = 0;
                int truecount = 0;
                    char c1 = '\0';
                    for (int k = 0; k < str.Length; k++)
                    {
                       c1 = str[k];

                        if (chars[j] == c1)
                        {
                            replace = true;
                            truecount ++;


                        }

                        else
                        {
                            truecount = 0;
                            replace = false;
                            j = 0;
                        }
                        if(truecount>0)
                        {
                            j++;
                        }

                        if (j > chars.Length-1)
                        {
                            j = 0;
                        }

                        if (truecount == chars.Length)
                        {
                            output.Remove(output.Length - chars.Length+1, chars.Length-1);
                           // output.Remove(4, 2);
                            if (replace)
                                output.Append(replacement);
                            else
                                output.Append(c1);
                        }
                        else
                        {
                            output.Append(c1);
                        }


                    }

            }


            return output.ToString();
        }


    static void Main(string[] args)
    {

        Console.WriteLine("Enter a word");
        string word = (Console.ReadLine());

        Console.WriteLine("Enter a word to find");
        string find = (Console.ReadLine());

        Console.WriteLine("Enter a word to Replace");
        string Rep = (Console.ReadLine());

        Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
        Console.ReadLine();

    }

}
0

Use the string.Replace(string old, string replacement) method.

 string input = "Add Additional String to text box";
 string output = input.replace("Add ", "Insert ");

 output == "Insert Additional String to text box" // true

If you need greater flexibility use RegEx, but since you want to replace an exact string the string.replace method should suffice.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 1
    No this will produce "Insert Insertitional String to text box" – Darshana Dec 14 '12 at 00:11
  • @Darshana It won't do what you're saying, because "Add" has to be followed by a space character, and the Add in Additional does not have a space after it. – hatchet - done with SOverflow Dec 14 '12 at 00:13
  • @Darshana no it won't. He included a white space. – Josh C. Dec 14 '12 at 00:14
  • 1
    if the word to replace is at the end, it won't work since it is missing a space. – João Simões Dec 14 '12 at 00:23
  • @JSimoes that is true. What I have is somewhat specific to that input. If you really want to make it work you have to check many other cases. Some crap input like "stringHereAdd" may also produce an unexpected result. When doing string replacements it's important to ensure your matching is sufficient. For the given input string that is. For any input, it's not. But he also doesn't define what a match is very well. – evanmcdonnal Dec 14 '12 at 00:26
0

If you want only to replace a full word, not correspondences inside another, you could do something like this:

// add a leading and tail space
string tmp = " " + "Add Additional String to text box"+ " ";
// replace the word you want, while adding a lead and tail space, and then Trim
tmp = tmp.Replace(" Add ", " Insert ").Trim();

Can't test now, but this may work.

João Simões
  • 1,351
  • 1
  • 10
  • 20