Character Analysis & Conversion Functions
ฟังก์ชันใน Library <ctype.h> ใช้สำหรับ **วิเคราะห์** และ **แปลง** ตัวอักษร
Analysis Functions (ตรวจสอบลักษณะตัวอักษร)
| No. | Function | Description | คืนค่า |
|---|---|---|---|
| 1 | isalpha(c) | เป็นตัวอักษร (A-Z, a-z) | Non-zero (True) / 0 (False) |
| 2 | isdigit(c) | เป็นตัวเลข (0-9) | Non-zero / 0 |
| 3 | isspace(c) | เป็น Whitespace (space, \t, \n, \v, \f, \r) | Non-zero / 0 |
| 4 | ispunct(c) | เป็น Punctuation (เครื่องหมายวรรคตอน) | Non-zero / 0 |
| 5 | islower(c) | เป็นตัวพิมพ์เล็ก (a-z) | Non-zero / 0 |
| 6 | isupper(c) | เป็นตัวพิมพ์ใหญ่ (A-Z) | Non-zero / 0 |
| 7 | isalnum(c) | เป็นตัวอักษรหรือตัวเลข | Non-zero / 0 |
| 8 | isxdigit(c) | เป็น Hex Digit (0-9, A-F, a-f) | Non-zero / 0 |
| 9 | iscntrl(c) | เป็น Control Character | Non-zero / 0 |
| 10 | isprint(c) | เป็น Printable Character (รวม Space) | Non-zero / 0 |
| 11 | isgraph(c) | เป็น Printable แต่ไม่รวม Space | Non-zero / 0 |
Conversion Functions (แปลงตัวอักษร)
| Function | Description |
|---|---|
tolower(c) | แปลงตัวพิมพ์ใหญ่ → พิมพ์เล็ก |
toupper(c) | แปลงตัวพิมพ์เล็ก → พิมพ์ใหญ่ |
ตัวอย่างโปรแกรม: วิเคราะห์ตัวอักษร
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("\n--- Analysis ---\n");
printf("isalpha: %d\n", isalpha(ch));
printf("isdigit: %d\n", isdigit(ch));
printf("isspace: %d\n", isspace(ch));
printf("ispunct: %d\n", ispunct(ch));
printf("islower: %d\n", islower(ch));
printf("isupper: %d\n", isupper(ch));
printf("isalnum: %d\n", isalnum(ch));
printf("\n--- Conversion ---\n");
printf("tolower: %c\n", tolower(ch));
printf("toupper: %c\n", toupper(ch));
return 0;
}
ผลลัพธ์ตัวอย่าง (Input: 'A'):
--- Analysis ---
isalpha: 1
isdigit: 0
isspace: 0
ispunct: 0
islower: 0
isupper: 1
isalnum: 1
--- Conversion ---
tolower: a
toupper: A
ตัวอย่างโปรแกรม: นับประเภทตัวอักษรใน String
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[100];
int alpha=0, digit=0, space=0, punct=0, other=0;
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
for (int i = 0; str[i]; i++) {
unsigned char c = str[i]; // Cast ป้องกัน UB กับ ctype.h
if (isalpha(c)) alpha++;
else if (isdigit(c)) digit++;
else if (isspace(c)) space++;
else if (ispunct(c)) punct++;
else other++;
}
printf("Alpha: %d, Digit: %d, Space: %d, Punct: %d, Other: %d\n",
alpha, digit, space, punct, other);
return 0;
}
⚠️ ข้อควรระวังสำคัญ
ต้อง Cast เป็นunsigned charก่อนส่งให้ ctype.h functions
isalpha((unsigned char)c)- มิฉะนั้นอาจเกิด Undefined Behavior กับค่าลบ (Signed Char)