我得到在形式RichTextBox控件和一个文本文件。我得到的文本文件,以阵列并获得richtextbox1.text到另一个阵列比进行比较和计算词的匹配。 但是,例如有在文本文件中的两个“名”字和三个“和”字在RichTextBox的。所以如果在文本文件中的两个相同的字在RichTextBox中它不能2后是3或更高,那一定是打错字如此它不能被计算在内。但是HashSet的是只计算不希望在文本文件中重复的唯一值。我想在文本文件中的每一个字比较RichTextBox中的话。(sorr,我的英语。)

这里我的代码;

        StreamReader sr = new StreamReader("c:\\test.txt",Encoding.Default);
        string[] word = sr.ReadLine().ToLower().Split(' ');
        sr.Close();
        string[] word2 = richTextBox1.Text.ToLower().Split(' ');
        var set1 = new HashSet<string>(word);
        var set2 = new HashSet<string>(word2);
        set1.IntersectWith(set2);

        MessageBox.Show(set1.Count.ToString());
有帮助吗?

解决方案

推断你想要的:

文件:

foo
foo
foo
bar

文本框:

foo
foo
bar
bar

以导致 '3'(2个FOOS和一个巴)

Dictionary<string,int> fileCounts = new Dictionary<string, int>();
using (var sr = new StreamReader("c:\\test.txt",Encoding.Default))
{
    foreach (var word in sr.ReadLine().ToLower().Split(' '))
    {
        int c = 0;
        if (fileCounts.TryGetValue(word, out c))
        {
            fileCounts[word] = c + 1;
        }
        else
        {
            fileCounts.Add(word, 1);
        }                   
    }
}
int total = 0;
foreach (var word in richTextBox1.Text.ToLower().Split(' '))
{
    int c = 0;
    if (fileCounts.TryGetValue(word, out c))
    {
        total++;
        if (c - 1 > 0)
           fileCounts[word] = c - 1;                
        else
            fileCounts.Remove(word);
    }
}
MessageBox.Show(total.ToString());

请注意,这是破坏性修改读字典,你可以做到这一点(所以只需要读取字典一次)购买简单地计算以同样的方式丰富的文本框,然后把个人计数的最小值,然后合计起来

其他提示

您需要的数是一样的吗?你需要来算的话,那么......

    static Dictionary<string, int> CountWords(string[] words) {
        // use (StringComparer.{your choice}) for case-insensitive
        var result = new Dictionary<string, int>();
        foreach (string word in words) {
            int count;
            if (result.TryGetValue(word, out count)) {
                result[word] = count + 1;
            } else {
                result.Add(word, 1);
            }
        }
        return result;
    }
        ...
        var set1 = CountWords(word);
        var set2 = CountWords(word2);

        var matches = from val in set1
                      where set2.ContainsKey(val.Key)
                         && set2[val.Key] == val.Value
                      select val.Key;
        foreach (string match in matches)
        {
            Console.WriteLine(match);
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top