-1

嗨,我是编码新手,我只想知道如何计算字符串中的特定字符,如“l”,计算后我只想给出结果。

尝试学习更多关于 C 语言编码的知识,以便为学校做一些研究。我只想创建一些图表,其中包含特定字符的百分比,例如:

  • 你好 <- 我们的字符串
  • l <- 我们的特殊性格

结果:这个“hello”字符串中有 2 l。

现在我的一些想法,因为人们不应该认为我没有做任何事情。

  • 读取字符串
  • 拆分字符,例如 h/e/l/l/o
  • 也许现在是一个循环来获取“l”的数量?
  • 如果找到“l” -> count+1
  • printf 表示 l 的数量

如果有人可以帮助我,我会非常高兴。

4

2 回答 2

4

你的算法很好;您需要帮助将您的伪代码转换为实际的 C 代码吗?如果是这样,你在这里,有大量的评论:

#include <stdio.h>

int main(void)
{
    char mystr[128]; // a char array, where the string will be input
    char ch; // the char we want to count
    char *p; // loop variable
    unsigned cnt; // number of occurrences

    fgets(mystr, sizeof(mystr), stdin); // read the string - max 128 characters, beware!
    ch = fgetc(stdin); // read the character
    cnt = 0;

    for (p = mystr; *p; p++) {
        if (*p == ch) cnt++; // walk through the string, increase the count if found
    }

    printf("%u occurrences found\n", cnt);

    return 0;
}
于 2013-01-08T19:55:31.053 回答
0

在 C 中 aString是一个类型为 的数组char。您可以遍历数组并与您自己的char进行比较。char

于 2013-01-08T19:56:07.580 回答