プログラミング+α学習ブログ

勉強したことの備忘録です。

文字列に特定文字が含まれているかどうかを調べるプログラム

#include <stdio.h>

/*--- 文字列strから文字cを検索し、最も先頭側の要素の添字を返す ---*/
int str_char(const char str[], int c)
{
    int i;
    
    for (i = 0; str[i] != '\0'; i++)
        if (str[i] == c)
            return (i);
    return (-1);
}

int main(void)
{
    int no;
    char ch[10];
    
    printf("英文字を入力してください:");
    scanf("%s", ch);
    
    no = str_char("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                  "abcdefghijklmnopqrstuvwxyz", ch[0]);
    
    if (no >= 0 && no <= 25)
        printf("それは英大文字の%d番目です。\n", no + 1);
    else if (no >= 26 && no <= 51)
        printf("それは英小文字の%d番目です。\n", no - 25);
    else
        printf("それは英文字ではありません。\n");
    
    return (0);
}

実行結果

英文字を入力してください:E
それは英大文字の5番目です。