How can I replace a specific word in C#?

2020-02-14 03:06发布

问题:

Consider the following example.

string s = "The man is old. Them is not bad.";

If I use

s = s.Replace("The", "@@");

Then it returns "@@ man is old. @@m is not bad."
But I want the output to be "@@ man is old. Them is not bad."

How can I do this?

回答1:

Here's how you'd use a regex, which would handle any word boundaries:

Regex r = new Regex(@"\bThe\b");
s = r.Replace(s, "@@");


回答2:

I made a comment above asking why the title was changed to assume Regex was to be used.

I personally try to not use Regex because it's slow. Regex is great for complex string patterns, but if string replacements are simple and you need some performance out of it, I'll try and find a way without using Regex.

Threw together a test. Running a million replacments with Regex and string methods.

Regex took 26.5 seconds to complete, string methods took 8 seconds to complete.

        //Using Regex. 
        Regex r = new Regex(@"\b[Tt]he\b");

        System.Diagnostics.Stopwatch stp = System.Diagnostics.Stopwatch.StartNew();

        for (int i = 0; i < 1000000; i++)
        {
            string str = "The man is old. The is the Good. Them is the bad.";
            str = r.Replace(str, "@@");
        }

        stp.Stop();
        Console.WriteLine(stp.Elapsed);

        //Using String Methods.
        stp = System.Diagnostics.Stopwatch.StartNew();

        for (int i = 0; i < 1000000; i++)
        {
            string str = "The man is old. The is the Good. Them is the bad.";

            //Remove the The if the stirng starts with The.
            if (str.StartsWith("The "))
            {
                str = str.Remove(0, "The ".Length);
                str = str.Insert(0, "@@ ");
            }

            //Remove references The and the.  We can probably 
            //assume a sentence will not end in the.
            str = str.Replace(" The ", " @@ ");
            str = str.Replace(" the ", " @@ ");
        }

        stp.Stop();
        Console.WriteLine(stp.Elapsed);


回答3:

s = s.Replace("The ","@@ ");



回答4:

C# console Application

static void Main(string[] args)

        {
            Console.Write("Please input your comment: ");
            string str = Console.ReadLine();
            string[] str2 = str.Split(' ');
            replaceStringWithString(str2);
            Console.ReadLine();
        }
        public static void replaceStringWithString(string[] word)
        {
            string[] strArry1 = new string[] { "good", "bad", "hate" };
            string[] strArry2 = new string[] { "g**d", "b*d", "h**e" };
            for (int j = 0; j < strArry1.Count(); j++)
            {
                for (int i = 0; i < word.Count(); i++)
                {
                    if (word[i] == strArry1[j])
                    {
                        word[i] = strArry2[j];
                    }
                    Console.Write(word[i] + " ");
                }
            }
        }