小编bez*_*nyl的帖子

计算一个字母在一个字符串中的重复次数

我正在开发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();
}
Run Code Online (Sandbox Code Playgroud)

输出:

“ 2,1,1,1,1,1,”

预期:

“ 1,1,1,1,1,1,”

因为每个字母在字符串中仅出现一次。

c# arrays for-loop

4
推荐指数
2
解决办法
146
查看次数

标签 统计

arrays ×1

c# ×1

for-loop ×1