用C#中的string1替换string2中的单词

时间:2014-04-03 09:52:10

标签: c#

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

string String1 = "This city is very beautiful"; 

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

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

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

两个字符串中的句子总是相同的,可能会在String2中出现拼写错误。

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

我认为你需要像拼写纠正器这样的东西。

Check this code

答案 2 :(得分:0)

这个比较每个单词,假设顺序正确,如果string2更长,则会附加string2的其余部分。

我确定它可以提高效率(特别是在长字符串上,使用stringbuilder等)。

修改:没有foreach

更新
        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);
        }