如何替换 C# 中的特定单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/884759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:19:14  来源:igfitidea点击:

How can I replace a specific word in C#?

c#regexstringreplace

提问by

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."

然后它返回"@@ man is old. @@m is not bad."
但我希望输出是"@@ man is old. Them is not bad."

How can I do this?

我怎样才能做到这一点?

回答by RedFilter

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

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

回答by Liron Yahdav

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

以下是您如何使用正则表达式,它可以处理任何单词边界:

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

回答by Chris Persichetti

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

我在上面发表了一条评论,询问为什么将标题更改为假设要使用 Regex。

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.

我个人尽量不使用正则表达式,因为它很慢。Regex 非常适合复杂的字符串模式,但如果字符串替换很简单并且您需要一些性能,我会尝试找到一种不使用 Regex 的方法。

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

一起做个测试。使用正则表达式和字符串方法运行一百万次替换。

Regex took 26.5 secondsto complete, string methods took 8 secondsto complete.

正则表达式需要26.5 秒才能完成,字符串方法需要8 秒才能完成。

        //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);

回答by Coder

C# console Application

C# 控制台应用程序

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] + " ");
                }
            }
        }