我找到了这样一个函数,对其进行了一些修改,但它似乎输出出现次数最多的参数,但我试图使其输出出现次数最少的字符。
void leastOften(int *s) {
int i, j;
int min[256] = {0} ;
int min_count = 1000;
for (i=0; i<256; i++) {
if (s[i]) {
if (s[i] < min_count) {
for (j=0; j<256; j++)
min[j]=0;
min[i]=1;
min_count = s[i];
} // 2nd_if
else if (s[i] == min_count)
min[i]=1;
} // 1st_if
} //1st_for
printf("The least appearing characters are: ");
for (i=0; i<256; i++) {
if (min[i])
putchar(i);
} //2nd_for
}
最佳答案
void lessOften(int *s)
这个函数正在查看一个整数数组,你的意思是查看一个字符数组。
请注意,有效的 ASCII 范围是 0 到 128 之间,在该范围内有许多字符从未出现过。例如,您不太可能有 ^
字符,它的出现次数为零。将会有许多字符不会出现,因此它们的数量最少。但你可能对这些角色不感兴趣。您可能希望将范围限制在 'A'
到 'Z'
和 'a'
到 'z'
之间> 等等
此函数查找至少出现一次的字符,并且它们出现次数最少:
#include <stdio.h>
#include <string.h>
void least(char *buf)
{
int i;
int len = strlen(buf);
int counter[256];
memset(counter, 0, sizeof(counter)); //initialize the counter
for (i = 0; i < len; i++) //find the occurence of each letter
counter[(unsigned char)buf[i]]++;
int min = 0xFFFF; //assing to a large number
for (i = 0; i < 256; i++)
if (counter[i] && counter[i] < min)
min = counter[i];
printf("character(s) which appear once, and the least often:\n");
for (i = 0; i < 256; i++)
if (counter[i] && counter[i] == min)
printf("%c ", (char)i);
printf("\n");
}
int main()
{
least("ABBCCDDEEFGG");
return 0;
}
关于出现最少的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454491/