해시 세트는 단어를 계산하지만 고유 한 것만 교차합니다

StackOverflow https://stackoverflow.com/questions/980073

  •  13-09-2019
  •  | 
  •  

문제

양식과 텍스트 파일로 RichTextBox 컨트롤을 받았습니다. 텍스트 파일을 배열로 가져 와서 RichTextBox1.text를 다른 배열에 비교하고 일치하는 단어를 계산합니다. 그러나 예를 들어 텍스트 파일에는 두 개의 "이름"이라는 단어와 3 번 "과"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 개와 막대 1 개)을 초래합니다.

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