首页 > 解决方案 > 找出多个最长的单词并计算它们重复的次数

问题描述

所以我编写了在两个文本文件中查找最长单词的代码,如果这是第一个文本文件中的唯一单词,它会写入文件。但是我需要在第一个文本文件中找到唯一的单词,然后从这些唯一的单词中找到 10 个最长的单词。然后这 10 个单词从最长到最短排序,并计算它在第一个文本文件中出现的次数。

        string[] LongestWrods(string[] longest1, string[] text2, int longestCount1, out int longestWordText, char[] @char)
    {
        string[] LongestWordsText1 = new string[10];
        longestWordText = 0;
        for (int i = 0; i < longestCount1; i++)
        {
            if (RepeatTimes(text2, longest1[i], @char) == 0)
                LongestWordsText1[longestWordText++] = longest1[i];
        }
        return LongestWordsText1;
    }

标签: c#word

解决方案


这边走:

class Program
{
    static void Main(string[] args)
    {
        List<string> wordsToCut = File.ReadAllLines("text2.txt").Distinct().ToList();

        List<UniqueWord> uniqueWords = new List<UniqueWord>();

        foreach (string word in File.ReadAllLines("text1.txt"))
        {
            if (wordsToCut.Contains(word) == false)
            {
                UniqueWord uniqueWord = uniqueWords.Where(x => x.Word == word).FirstOrDefault();

                if (uniqueWord != null)
                {
                    uniqueWord.Occurrence++;
                }
                else
                {
                    uniqueWords.Add(new UniqueWord(word));
                }
            }
        }

        uniqueWords = uniqueWords.OrderByDescending(x => x.Word.Length).Take(10).ToList();
    }
}

public class UniqueWord
{
    public string Word { get; set; }
    public int Occurrence { get; set; }

    public UniqueWord(string word)
    {
        Word = word;
        Occurrence = 1;
    }
}

推荐阅读