C# String.Contains()未从For循环列表项中找到匹配项

C# String.Contains()未从For循环列表项中找到匹配项,c#,arrays,list,for-loop,C#,Arrays,List,For Loop,我将一个字符串拆分为一个数组,前面的每个单词与下一个单词对应 字符串1:地球是距离太阳的第三颗行星。 The The Earth The Earth is The Earth is the The Earth is the third The Earth is the third planet The Earth is the third planet from The Earth is the third planet from the The Earth is the third plane

我将一个
字符串
拆分为一个
数组
,前面的每个单词与下一个单词对应

字符串1:
地球是距离太阳的第三颗行星。

The
The Earth
The Earth is
The Earth is the
The Earth is the third
The Earth is the third planet
The Earth is the third planet from
The Earth is the third planet from the
The Earth is the third planet from the sun.

我想在第二个字符串中搜索列表中的匹配项

字符串2:
地球是我们生活的星球。

匹配应该是
地球就是


但是,我的
string.Contains()
没有从
变体[m]
检测到匹配

C#

string sentence1=“地球是距离太阳第三颗行星。”;
string sentence2=“地球是我们赖以生存的星球。”;
string[]words=sentence1.Split(“”);
列表变体=新列表();
//单词变体列表
//
字符串组合=string.Empty;
for(var i=0;i
在第一个单词(
i=0
)上运行此语句时,会将空字符串与
单词[0]
连接起来

这会导致在第一个单词之间有一个额外的空格

简单的解决办法是

if (i == 0) {
    combined = words[i];
} else {
    combined = string.Join(" ", combined, words[i]);
}

也就是说:您正在检查它是否是第一个单词,并相应地采取行动。

您的
变体[m]
以空格开头。@zerkms谢谢,我没有注意到这一点。TrimStart()似乎已经解决了这个问题。是的,只是不要添加它或
TrimStart
combined = string.Join(" ", combined, words[i]);
if (i == 0) {
    combined = words[i];
} else {
    combined = string.Join(" ", combined, words[i]);
}