String.Contains() 找不到来自 For 循环列表项的匹配项



我将一个string拆分为一个array,每个前一个单词与下一个单词连接。

字符串 1:The Earth is the third planet from the sun.

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:The Earth is the planet we live on.

匹配应该是The Earth is the


但是,我的string.Contains()没有检测到variations[m]的匹配项。

http://rextester.com/BDYV53887

C#

string sentence1 = "The Earth is the third planet from the sun.";
string sentence2 = "The Earth is the planet we live on.";
string[] words = sentence1.Split(' ');
List<string> variations = new List<string>();

// List of Word variations
//
string combined = string.Empty;
for (var i = 0; i < words.Length; i++)
{
    combined = string.Join(" ", combined, words[i]);
    variations.Add(combined);
}
// Words Match
//
string match = string.Empty;
for (int m = 0; m < variations.Count; m++)
{
    if (sentence2.Contains(variations[m])) // not working, "The Earth is the" not found
    {
        match = variations[m];
    }
}
combined = string.Join(" ", combined, words[i]);

此语句在第一个单词 (i = 0( 上运行时将空字符串与 words[0] 连接起来。

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

直接的解决方法是

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

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

最新更新