【发布时间】:2019-12-09 02:24:50
【问题描述】:
我正在编写 CodeWars 上的 Kata,我必须计算每个字母在字符串中的重复次数。重复次数应存储在 int 数组中。
我编写的算法似乎几乎可以工作,但是我得到了一个我无法解释的奇怪输出。我可能在代码中遗漏了一些东西。
static void Main(string[] args)
{
string str = "abcdef";
string input = str.ToLower();
int count = 0;
string[] arrayInput = Regex.Split(input, string.Empty);
string[] alphabet = Regex.Split("abcdefghijklmnopqrstuvwxyz", string.Empty);
int[] amounts = new int[input.Length];
foreach (string letter in alphabet)
{
for (int x = 0; x < input.Length; x++)
{
if (arrayInput[x] == letter)
{
amounts[x]++;
}
}
}
foreach (int amount in amounts)
{
Console.Write(amount + ", ");
}
Console.ReadKey();
}
输出:
"2, 1, 1, 1, 1, 1,"
预期:
"1, 1, 1, 1, 1, 1,"
因为每个字母在字符串中只出现一次。
【问题讨论】:
-
我建议使用调试器单步执行代码;没有什么比准确地看到你在代码中混淆的地方更好了。
-
我可以建议的一件事是将行数量[x]++ 更改为数量[x] = 数量[x] + 1
-
Console.Write(string.Join(", ", str.ToLower().GroupBy(c => c).Select(group => group.Count()));