谁能告诉我我的代码有什么问题?
基本上,在比较 words1
和 words2
之后,我只需要将 words1
中的唯一单词添加到 uniques
列表中.
在 if
语句中,如果我删除 !
然后它会找到匹配的词(与我需要的相反)
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
List<string> uniques = new List<string>();
for (int i = 0; i < words1.Length; i++)
{
bool match;
for (int x = 0; x < words2.Length; x++)
{
if (!words1[i].Equals(words2[x]))
{
match = true;
uniques.Add(words1[i]);
break;
}
else
{
match = false;
}
}
}
return uniques;
}
最佳答案
你可以对你的循环做一些小改动
for (int i = 0; i < words1.Length; i++)
{
bool match=false;
for (int x = 0; x < words2.Length; x++)
{
if (words1[i].Equals(words2[x]))
{
match = true;
break;
}
}
if(!match && uniques.Contains(words1[i]))
{
uniques.Add(words1[i]);
}
{
uniques.Add(words1[i]);
}
}
要使您的代码更短,您可以使用 LINQ
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return words1.Except(words2).ToList();
}
关于c# - 找不到独特的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461449/