出现最少的角色

标签 c if-statement for-loop

我找到了这样一个函数,对其进行了一些修改,但它似乎输出出现次数最多的参数,但我试图使其输出出现次数最少的字符。

 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/

相关文章:

c - 为什么 struct int 值没有被传递到下一个函数?

dup2 上的困惑

c - 将十六进制操作码解码为 asm 或在 __asm 中运行十六进制?

java - 仅在最后一次迭代时输出 For 循环的值

通过 PPM 在 C 中创建标志

c++ - 将用户输入的 int 作为大小,将 int 作为数组,然后显示数组,最后一个索引到第一个索引

for-loop - ffmpeg/for 循环 : How to make ffmpeg or cmd loop stops after it founds an error?

c - 接收 SIGSEGV 的程序可能是针对 0xffffffff 的指针

javascript - 下拉菜单和单选按钮未得到验证

R 仅在多列重叠的情况下合并数据帧