我试图计算在我的字节数组中出现一个字节的次数,将其写入uint [],这样我的输入就是。编写abcabcabc的byte[] arrayToConvert = {97, 98, 99, 97, 98, 99, 97, 98, 100};
。
我试图使用uint[]
实现的是:
97 = 3 times
98 = 3 times
99 = 2 times
100 = 1 time
所以我试着在我的课堂上这样做:
public static uint[] mCount(byte[] aCount)
{
for (int i = 0; i < aCount.Length; i++)
{
for (int j = i; j < aCount.Length; j++)
{
if (aCount[i] == aCount[j])
{
// somewhere arround here I think I must create the uint[] to return.
// but for this I would need to know howmany different bytes there are.
// not to forget I need to get my counter working to safe howmany of wich byte there are.
uint[] returncount = new uint[ !! number of different bytes !! ];
// foreach to fill the ^ array.
count = count + 1;
}
}
}
return returncount;
}
所以此时我完全卡住了。所以,如果有人能够帮助我朝着正确的方向努力,那就太好了。或者告诉我在哪里可以阅读有关此内容以便更好地学习它。因为我似乎无法找到我理解的解释。
在此先感谢您的编码!
首先,您应该注意到一个字节的范围是0到255。
我认为最好的方法之一是声明一个int(这里的类型并不重要)大小为256的数组并将每个元素初始化为0。
然后,只需迭代输入数组中的每个元素,使用它作为新创建的数组的索引并递增其值。最后,int数组的每个元素都将包含其输入索引的出现。
例如:
var aCount = new[] {97, 98, 99, 97, 98, 99, 97, 98, 100};
var occurrences = new int[256];
for (int i = 0; i < aCount.Length; i++)
{
var byteElement = aCount[i];
occurrences[byteElement]++;
}
for (int i = 0; i < occurrences.Length; i++)
if (occurrences[i] != 0)
Console.WriteLine($"{i} = {occurrences[i]} times");