首页 > 解决方案 > 找不到独特的词

问题描述

谁能告诉我我的代码有什么问题?基本上,在比较和之后,我只需words1要从列表中添加唯一的单词。在语句中,如果我删除,那么它会找到匹配的单词(与我需要的相反)uniqueswords1words2if!

    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;
    }

标签: c#string-matching

解决方案


你可以对你的循环做一些小的改动

    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();
}

推荐阅读