我将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.
我想从List中搜索第二个字符串以获得匹配。
字符串2:The Earth is the planet we live on.
匹配应为The Earth is the
。
但是我的string.Contains()
未检测到来自variations[m]
的匹配。
https://www.codeigniter.com/user_guide/general/routing.html#examples
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];
}
}
答案 0 :(得分:1)
combined = string.Join(" ", combined, words[i]);
在第一个单词(i = 0
)上运行时,此语句将空字符串与words[0]
连接。
这会让你在第一个单词之间留出一个额外的空格。
直截了当的解决方案是
if (i == 0) {
combined = words[i];
} else {
combined = string.Join(" ", combined, words[i]);
}
即:您正在检查它是否是第一个字,并相应地采取行动。