在 C# 中将字符串 2 中的单词替换为字符串 1

本文关键字:字符串 替换 单词 | 更新日期: 2023-09-27 17:56:26

假设我有两个字符串。 String1包含拼写正确的字符串,String2包含一些错误的字符串。

string String1 = "This city is very beautiful"; 
string String2 = "The citi is very beautyful - and its also very big:";

因为String1包含拼写正确的字符串。我想用String1替换String2中的单词,所以最后我应该有。

String2 = "This city is very beautiful - and its also very big:";

两个字符串中的句子将始终相同,String2中可能会出现拼写错误。

在 C# 中将字符串 2 中的单词替换为字符串 1

这是基于您的问题:

String2 = String2.Replace("The citi is very beautyful", String1);
// You can also do it this way
String2 = String2.Replace("The citi is very beautyful", "This city is very beautiful");

这个比较每个单独的单词,假设顺序正确,如果 string2 更长,字符串 2 的其余部分将被附加。

我相信它可以提高效率(特别是在长字符串上,使用字符串生成器等)。

编辑:更新而不更新

        string s1 = "This city is very beautiful";
        string s2 = "The citi is very beautyful - and its also very big:";
        if (!string.IsNullOrEmpty(s2) && s2.Contains(' '))
        {
            string[] partsS1 = s1.Split(' ');
            string[] partsS2 = s2.Split(' ');
            int count = partsS1.Length;
            for (int a = 0; a < count; a++)
            {
                if (partsS2.Length > count)
                {
                    if (partsS1[a] != partsS2[a])
                    {
                        partsS2[a] = partsS1[a];
                    }
                }
            }
            string final = string.Empty;
            foreach (string s in partsS2)
            {
                final += s + " ";
            }
            final = final.TrimEnd(' ');
            Console.WriteLine(final);
        }

我认为你需要一个拼写校正器之类的东西。

检查此代码