首页 > 解决方案 > 使用 C# 计算每个字符串在字符串数组中出现的次数

问题描述

为此,我将文本文件中的代码作为字符串派生,并且我想计算每个字符串的频率。我让计数器循环,但如果计数器会多次显示结果。

如何让它识别唯一的字符串? 我希望它显示这个:

数字 1 出现 1 次

数字 2 出现 4 次

数字 4 出现 3 次

但它现在正在显示:

数字 1 出现 1 次

数字 2 出现 4 次

数字 2 出现 4 次

数字 2 出现 4 次

数字 2 出现 4 次

数字 4 出现 3 次

数字 4 出现 3 次

数字 4 出现 3 次

void Start()
{
    string Random = "";

    // Read text 
    string Numbers_Path = Application.dataPath + "/Text_Files/Numbers.txt";
    string[] Duplicates = File.ReadAllLines(Numbers_Path);

    foreach (string number in Duplicates)
    {
        Random += number;
    }

    //output display text_file
    NumOutput.text = Random + "\n";

    Array.Sort(Duplicates);

    for (int x = 0; x < Duplicates.Length; x++)
    {
        count = Duplicates.Count(n => n == Duplicates[x]);
        Display += "The number " + Duplicates[x] + " appears " + count + " time/s" + "\n";
    }
            Results.text = Display;

标签: c#

解决方案


您可以使用Enumerable.GroupBy按值对行进行分组(此处的文本值应该足够了)。例如,

foreach(var number in Duplicates.GroupBy(x=>x))
{
    Console.WriteLine($"The number {number.Key} has appeared {number.Count()} times");
}

将解决方案分成几部分,**

第 1 步:从文本文件中读取输入

var Duplicates = File.ReadAllLines(Numbers_Path);

在此处输入图像描述

第 2 步:按值对重复集合进行分组

Duplicates.GroupBy(x=>x)

在此处输入图像描述

输出:最终结果

The number 1 has appeared 3 times
The number 2 has appeared 2 times
The number 3 has appeared 3 times
The number 5 has appeared 2 times

推荐阅读