bez*_*nyl 4 c# arrays for-loop
我正在开发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,”
因为每个字母在字符串中仅出现一次。
当quering,LINQ的往往是不错的选择:
using System.Linq;
...
string str = "abcdef";
// {1, 1, 1, 1, 1, 1} - each letter appears once
int[] result = str
.ToLower()
//.Where(c => c >= 'a' && c <= 'z') // uncomment, if we want 'a'..'z' range only
.GroupBy(c => c)
.Select(group => group.Count())
.ToArray();
Console.Write(string.Join(", ", result));
Run Code Online (Sandbox Code Playgroud)
我认为您犯了一个错误:
int[] amounts = new int[input.Length];
Run Code Online (Sandbox Code Playgroud)
应该
int[] amounts = new int[26];
Run Code Online (Sandbox Code Playgroud)
而且您的循环不太正确。
您无需将字符串拆分为字符串数组。您可以只使用字符串迭代器来获取每个字符。同样,如果您在非常大的字符串上执行此操作,则对于不需要遍历整个字母的每个字符,解决方案的效率都会很低。
您可以大大简化您编写的内容:
string input = "abcdef";
int[] counts = new int[26];
foreach (var ch in input)
{
var c = char.ToLower(ch);
if (c >= 'a' && c <= 'z')
counts[c - 'a']++;
}
Run Code Online (Sandbox Code Playgroud)