【问题标题】:Algorithm question for c# (displaying every number of digits using string.split)c#的算法问题(使用string.split显示每个数字)
【发布时间】:2021-10-23 13:18:15
【问题描述】:

假设我们有 1 到 20 的整数。我必须打印出这样的内容:

Number of 1: 13
Number of 2: 5
Number of 3: 5
.
.
Number of 9: 2

我使用了string.split方法like this

如何使用整数数组实现这一点并使用 for 循环向前推进?或者有没有更好的方法来解决这个问题?

【问题讨论】:

  • 感谢您的反馈。这是我在 stackoverflow 上的第一个问题,所以我还在学习中
  • 您的str 不包含任何数字("The Engineering Projects"),您的要求不清楚。此外,当您在 for 条件中使用 count < strArr.Length-1 时,您的示例将仅显示 "The""Engineering"(跳过 "Projects"

标签: c# algorithm split numbers digits


【解决方案1】:

有没有更好的方法来解决这个问题?

是的,有更好的方法来实现您想要实现的目标。

这是我的尝试:

我建议使用Dictionary<int, int> 来存储整数及其与数字的计数。

var result = Enumerable.Range(1, 20) //Iterate from 1 to 20
            .SelectMany(x => x.ToString()) //create an array from [1..20]
            .GroupBy(x => x)  //Group by element, so that you will get count
            .ToDictionary(x => x.Key, x => x.Count()); //Store it in dictionary

foreach(var item in result)
    Console.WriteLine($"Number of {item.Key} : {item.Value}");

.NET Fiddle

【讨论】:

  • @Tanokt,我很高兴我的解决方案适合你。请注意:请使用minimal reproducible example 更新您的问题,以便其他人从中受益。目前,真的很难理解您的期望以及您的输入是什么
猜你喜欢
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 2023-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
相关资源
最近更新 更多