文字列に含まれる特定文字の個数を返すプログラム
#include <stdio.h> /*--- 文字列str中の文字cの個数を返す ---*/ int str_chnum(const char str[], int c) { int i; int count = 0; for (i = 0; str[i] != '\0'; i++) if (str[i] == c) count++; return (count); } int main(void) { char str[256]; char ch[10]; printf("文字列を入力してください:"); scanf("%s", str); printf("検索する文字を入力してください:"); scanf("%s", ch); printf("その文字は%d個含まれています。\n", str_chnum(str, ch[0])); return (0); }
実行結果
文字列を入力してください:opqrst 検索する文字を入力してください:r その文字は1個含まれています。