C言語で文字型を判定する方法
C言語では、以下の2つの方法で文字の種類を判定できます。
- isalpha、isdigit、isalnum、islower、isupper といった標準ライブラリ関数は、引数で与えられた文字がそれぞれの型に属するかどうかを判定します。これらの関数は真の場合非ゼロ値を、偽の場合ゼロを返します。例えば、
#include <ctype.h>
#include <stdio.h>
int main() {
char ch = 'A';
if (isalpha(ch)) {
printf("Character is an alphabet.\n");
} else {
printf("Character is not an alphabet.\n");
}
if (isdigit(ch)) {
printf("Character is a digit.\n");
} else {
printf("Character is not a digit.\n");
}
return 0;
}
結果の出力が表示される
Character is an alphabet.
Character is not a digit.
- 文字の種別は、文字のASCIIコード値で判断します。例えば、英字は65-90と97-122、数字は48-57の範囲です。文字のASCIIコード値がこれらの範囲にあるかどうかで、文字の種別を判断できます。例えば、
#include <stdio.h>
int main() {
char ch = 'A';
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
printf("Character is an alphabet.\n");
} else {
printf("Character is not an alphabet.\n");
}
if (ch >= '0' && ch <= '9') {
printf("Character is a digit.\n");
} else {
printf("Character is not a digit.\n");
}
return 0;
}
日本語でネイティブに言い換えると:
Character is an alphabet.
Character is not a digit.
どちらの方法を選択するかは、具体的なニーズや個人の好みに依存します。