如何计算一个字母在字符串中出现的次数? C编程

How do I count how many times a letter appears in a string? C programming

我正在尝试编写一个程序来告诉我短语 "Yesterday, all my troubles seemed so far away" 中有多少 'e' 个字母。我正在尝试使用 strcmp 函数执行此操作,我想将短语中的每个字母与字母 'e' 进行比较,然后进行比较,以便计数递增。

int main(void) {
  int i, x, count = 0;
  char words[] = "Yesterday, all my troubles seemed so far away", letter;
  char str1 = "e";
  for (i = 0; i < 45; i++) {
    letter = words[i];
    x = strcmp(letter, str1);
    if (x == 0) {
      count++;
    }
  }
  printf("The number of times %c appears is %d.\n", str1, count);
}

您可以简单地将字符串字符与字符 'e' 进行比较,就像这样

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

int main(void)
{
    int i, count = 0;
    char words[] ="Yesterday, all my troubles seemed so far away";

    for (i = 0; i < strlen(words); i++){
        if (words[i] == 'e') {
            count++;
        }
    }
    printf("The number of times %c appears is %d.\n", 'e', count);
}

对于初学者来说,使用函数strcmp来计算一个字符在字符串中出现的次数是一个坏主意。相反,您应该使用函数 strchr.

这个声明

char str1 = "e";

无效。在此声明中,指向字符串文字 "e" 的第一个字符的指针被转换为没有意义的 char 类型的对象。

strcmp

的来电
x = strcmp(letter, str1);

需要两个 const char * 类型的参数,而在此语句中传递了两个 char 类型的对象。因此调用会调用未定义的行为。

您可以按照下面的演示程序所示的方式编写一个单独的函数。

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

size_t letter_count( const char *s, char c )
{
    size_t n = 0;

    if ( c != '[=12=]' )
    {
        for ( const char *p = s; ( p = strchr( p, c ) ) != NULL; ++p )
        {
            ++n;
        }
    }

    return n;
}

int main(void) 
{
    char words[] = "Yesterday, all my troubles seemed so far away";

    char c = 'e';

    printf( "The number of times %c appears is %zu.\n", 
            c, letter_count( words, c ) );

    return 0;
}

程序输出为

The number of times e appears is 6.