我目前正在开展一个学校项目,我想为字符串创建频率分析,以便我们可以对它们进行编码或解码。 我需要以某种方式计算每个字符在字符串中出现的次数,srig 是一个随机文件,可以是书本或其他内容中的整页,因此我们需要 ascii 表中的所有字符。 现在我正在努力让一个数组充满所有可能出现的字符。
我决定采用包含一个 char 和一个 int 的结构体数组的方向,在我的脑海中,该结构体数组应该起作用,以便 char 是关键,而 int 是特定 char 出现的次数字符串。 我需要将所有 256 个可能的字符放入数组中,但无法找到获取前 32 个字符的方法。
for (char c = NULL; c <= 'z' ; c++){
ftabel[i].value = c;
i++;
}
我以为我可以做一些像这样简单的事情,但它不起作用。如果我让循环从 ” “它工作得很好。我也不知道该为 ascii 的最后一个元素添加什么。感谢所有帮助。
最佳答案
这实际上几乎是微不足道的,因为 char
值本身就是您需要的所有索引:
#include <limits.h>
// static, so it's initialized to zero
unsigned long long charCounts[ UCHAR_MAX + 1 ];
// Note the use of **unsigned** char
// `unsigned char` ensures any `char` value will
// not cause an improper access to charCounts[]
void countChars( const unsigned char *str )
{
while ( *str )
{
( charCounts[ *str ] )++;
str++;
}
}
int main( int argc, char **argv )
{
.
.
.
迂腐地说,只有 128 个真正的 ASCII 字符,但为此指定“ASCII”的人可能没有意识到这一点,并且可能意味着 "extended ASCII"某种类型和完整的 256 个字符。
如果您想打印出实际的 char
本身,那么打印 char
值并不简单 - 并非所有 char
值都是可打印的,有些可能会导致显示问题,具体取决于您的输出设备。这会有点作用:
#include <ctype.h>
void printCounts()
{
// unsigned char ii here would infinite loop...
// (yes, pedantically even `unsigned int` might)
for ( unsigned int ii = 0; ii <= UCHAR_MAX; ii++ )
{
// get a printable char value
unsigned char pp = ii;
if ( !isprint( ii ) )
{
pp = '*';
}
printf( "'%c' (%02X): %llu\n", pp, ii, charCounts[ ii ] );
}
}
.
.
.
关于c - C中的频率分析,如何获取数组中的整个ascii表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59933413/