c - C 计算字符串中字符数的函数

标签 c string

我是 C 新手。我想获得帮助以完成我的功能。

使命是:

编写一个接受字符串的函数最大长度为 256 个字符,包含从 'a' 到 'z' 的字符

打印每个字符出现次数的函数。

例如:输入 abba 输出将是:

a = 2 b = 2 c = 0 d = 0 .... z = 0

不要在任何函数中使用 if。

我想得到你的帮助来完成这个程序。

这是我的代码

#include "stdlib.h"
#include "conio.h"
#include "stdio.h"
#include "string.h"
#define size 256



void repeat(char *str);
void main()
{
    char str[size];
    printf("Please enter a string:\n");
    flushall;
    gets(str);
    repeat(str);
    system("pause");
    return ;
}
void repeat(char *str)
{

    char temp=strlen(str);
    int i, count=0;
    do
    {
    for (i=0; i<temp ; i++)
        {
            count += (*str == str[temp-i]);
        }
    printf("Char %c appears %d times\n ",*str,count);
    count=0;
    }
    while(*(str++));
}



    Please enter a string:
abbba
Char a appears 1 times
 Char b appears 2 times
 Char b appears 1 times
 Char b appears 0 times
 Char a appears 0 times
 Char   appears 0 times
 Press any key to continue . . .

这是输出! 我想在我做过的同一栋楼里做。 应该像 字符a出现2次 字符b出现3次

最佳答案

您规定不使用if。这满足了该限制。

#include <stdio.h>

int main(void) {
    int i, c;
    int counts[256] = { 0 };
    const char lower[] = "abcdefghijklmnopqrstuvwxyz";
    while ((c = getchar()) != EOF) {
        counts[c] += 1;
    }
    for (i = 0; lower[i]; ++i) {
        c = lower[i];
        printf("Char %c appears %d times.\n", c, counts[c]);
    }
    return 0;
}

您尝试的问题在于您没有跟踪任何状态来记住您已经打印了哪些字符的信息。它也没有将考虑中的字符包括在计数中。它还多次遍历字符串以收集有关每个字符的计数信息,但这不会影响正确性,只会影响性能。如果您能以某种方式记住您已经为哪个字符打印出信息,这样当相同的字符稍后出现在字符串中时您就不会再次这样做,您的方法应该打印出出现的字符的计数。之后,您需要为根本没有出现的字符打印出零计数。如果输出需要按字母顺序排列,那么您也需要确保自己处理好这一点。

正确跟踪信息并允许按字母顺序打印输出的一种方法是维护数组中每个字符的计数。遍历字符串并递增与每个找到的字符关联的计数后,您可以迭代计数数组,并打印出计数。


以下程序适用于 zubergu:

#include <stdio.h>
#include <string.h>

int main (void) {
    int i, c;
    int counts[26] = { 0 };
    const char lower[] = "abcdefghijklmnopqrstuvwxyz";
    while ((c = getchar()) != EOF) {
        switch (c) {
        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
        case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
        case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
        case 'v': case 'w': case 'x': case 'y': case 'z':
            counts[strchr(lower, c) - lower] += 1;
            break;
        default:
            break;
        }
    }
    for (i = 0; lower[i]; ++i) {
        printf("Char %c appears %d times.\n", lower[i], counts[i]);
    }
    return 0;
}

关于c - C 计算字符串中字符数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18694086/

相关文章:

python - 将多行字符串的每一行发送到 for 循环中的列表

python - 如何替换 Python 字符串中的单词

java - 分割后字符串变成空白

c# - 如何制作字符串“,”?

c - 我想获取用户输入并返回每个字符串的第一个字母

c - Node FFI 包装函数在同步使用时失败,但异步工作

c - 结构的陷阱表示

c - 打印语句如何在这里执行四次?

c - 如何在 c 中向 gnuplot 传递矩阵?

java - 如何验证/比较 Selenium 中的 2 个值?