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

6
考虑以下例子。
string s = "The man is old. Them is not bad.";

如果我使用
s = s.Replace("The", "@@");

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

我该怎么做?


为什么标题被编辑以包括Regex?文本替换有多种方法。我通常尽量避免使用Regex,因为它很慢,所以我认为标题不应该被编辑以包括“假定”的答案。 - Crispy
1
@Chris Persichetti:很好,我已经从标题中删除了“regex”(我是根据标签添加的,但显然“regex”本来就不是原始标签之一)。 - Michael Myers
4个回答

23

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

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

4

我之前留言询问为什么标题被改成默认使用正则表达式。

个人尽量避免使用正则表达式,因为它的速度较慢。如果字符串替换很简单,且需要一定的性能,我会尝试寻找不使用正则表达式的方法。正则表达式非常适用于复杂的字符串模式匹配。

我进行了一个测试。使用正则表达式和字符串方法进行一百万次替换操作。

正则表达式用时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);

2
对于给定的数据,您提供的冗长解决方案是有效的。但是,除了比使用(诚然较慢的)正则表达式更不简洁之外,如果OP想要在更一般的情况下使用它,您的代码将失败或需要更新,而正则表达式可以编写以查找单词分隔符,这将处理像标点符号这样的分隔符而不仅仅是空格。请参见我的评论@auujay的帖子中的具体内容。 - JeffH
1
我知道这不是一个通用的解决方案。对于一般单词,正则表达式解决方案更安全。我主要想指出,正则表达式并不总是解决方案,这取决于确切需要什么。我尝试关注这样的问题,以获取文本替换的提示,因为我的项目需要大量文本替换,我一直在寻找更快的方法来完成它。所以当标题被更改为Regex时,我感到失望,因为我不想要一个正则表达式解决方案,这就是我发布这个答案的原因。 - Crispy
@Crispy,你不能只关注性能时间,软件不仅仅是快速运行,如果你不关心可读性和可维护性,你会创建一个更快的软件,但非常昂贵并且难以发展。 - Claudio Santos

3

将 s 中的 "The " 替换为 "@@ "。


0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接