假设我有两个字符串。 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
中出现拼写错误。
答案 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)
我认为你需要像拼写纠正器这样的东西。
答案 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);
}