计算每个字符串使用C#出现在字符串数组中的次数

问题描述 投票:0回答:3

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

如何识别唯一的字符串?我希望它显示此内容:

数字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#
3个回答
0
投票

如果由于任何其他原因不需要按原始顺序使用它们,则可以使用Dictionary<string, int>

如果从文件中得到一个字符串,则检查它是否已经在Collection中-如果是,则将该值增加1。如果不是,则将其添加到值为0的collection中。在读取文件时,甚至可能使用枚举器遍历所有行。

我也不会担心性能。 Dictionary<Key, Value>在内部也是通用的HashTable-因此在搜索和添加过程中通常不需要字符串比较。最重要的是,字符串是不可变的并且可以被插入。因此,逻辑应该适当地行进:

  • 哈希比较
  • 参考比较
  • 实际上是那些字符

0
投票

您正在寻找Distinct(简化为唯一元素)或GroupBy(按某些条件划分为组)。See the LINQ reference了解更多详情。

例如,使用后者可能看起来像:

var counts = Duplicates
    .GroupBy(x => x)  // We're grouping by uniqueness, so use the entire value 
    .Select(g => $"{g.First()} appears {g.Count()} times");
Results.text = string.Join("\n", counts);

0
投票

您可以使用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);

enter image description here

步骤2:按值对重复收集进行分组

Duplicates.GroupBy(x=>x)

enter image description here

输出:最终结果

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
© www.soinside.com 2019 - 2024. All rights reserved.