efrei/programmation-c-cpp/tp5/count_chars.c

39 lines
771 B
C
Raw Normal View History

2021-11-29 09:17:59 +01:00
/* Count chars */
#include <stdio.h>
#include <stdlib.h>
int count_chars(char, char*);
int main() {
char *chaine = "Hello world!";
char caractere;
int count;
caractere = 'e';
count = count_chars(caractere, chaine);
printf("Chaine: %s\n", chaine);
printf("Le caractère '%c' est présent %d fois.\n", caractere, count);
caractere = 'l';
count = count_chars(caractere, chaine);
printf("Chaine: %s\n", chaine);
printf("Le caractère '%c' est présent %d fois.\n", caractere, count);
return 0;
}
int count_chars(char caractere, char *chaine) {
int i = 0;
int count = 0;
while (chaine[i] != '\0') {
if (chaine[i] == caractere) {
count++;
}
i++;
}
return count;
}