ฟังก์ชัน isupper() ตรวจสอบว่าตัวอักษรเป็น ตัวพิมพ์ใหญ่ (Uppercase A-Z) หรือไม่ อยู่ใน Header <ctype.h>
ไวยากรณ์
#include <ctype.h>
int isupper(int c);
- Parameter:
int c- ตัวอักษรที่ตรวจสอบ (ต้องเป็นunsigned charหรือEOF) - คืนค่า: Non-zero (True) ถ้าเป็น Uppercase, 0 (False) ถ้าไม่ใช่
ตัวอย่าง
#include <stdio.h>
#include <ctype.h>
int main() {
char val1 = 's'; // Lowercase
char val2 = 'S'; // Uppercase
if (isupper(val1))
printf("'%c' is uppercase\n", val1);
else
printf("'%c' is NOT uppercase\n", val1);
if (isupper(val2))
printf("'%c' is uppercase\n", val2);
else
printf("'%c' is NOT uppercase\n", val2);
return 0;
}
ผลลัพธ์
's' is NOT uppercase
'S' is uppercase
ตาราง Character Classification (ctype.h)
| ฟังก์ชัน | ตรวจสอบ | True สำหรับ |
|---|---|---|
isupper() | Uppercase Letter | A-Z |
islower() | Lowercase Letter | a-z |
isalpha() | Alphabetic | A-Z, a-z |
isdigit() | Decimal Digit | 0-9 |
isalnum() | Alphanumeric | A-Z, a-z, 0-9 |
isxdigit() | Hex Digit | 0-9, A-F, a-f |
isspace() | Whitespace | Space, \t, \n, \v, \f, \r |
iscntrl() | Control Character | ASCII 0-31, 127 |
ispunct() | Punctuation | Printable but not Alnum/Space |
isprint() | Printable | Graphical + Space |
isgraph() | Graphical | Printable - Space |
Locale Dependency
พฤติกรรมของ isupper() ขึ้นกับ Current Locale (LC_CTYPE)
#include <locale.h>
#include <ctype.h>
setlocale(LC_CTYPE, "th_TH.UTF-8"); // Thai Locale
// isupper() จะรู้จักตัวอักษรไทยที่เป็นพิมพ์ใหญ่ (ถ้ามีใน Locale)
C++ Versions (Header )
#include <cctype>
#include <locale>
int main() {
char c = 'A';
// C-style (Global Locale)
std::isupper(c); // หรือ ::isupper(c)
// C++ Locale-aware (แนะนำ)
std::locale loc;
std::cout << std::isupper(c, loc) << std::endl;
return 0;
}
ข้อควรระวัง: Undefined Behavior
// อันตราย: char อาจเป็น Signed (-128..127)
char c = getchar(); // อาจได้ค่าลบ (Extended ASCII)
isupper(c); // UB! ค่าลบไม่ใช่ unsigned char/EOF
// ปลอดภัย: Cast เป็น unsigned char
isupper((unsigned char)c);
// หรือใช้ int ตรงๆ
int c = getchar();
isupper(c); // Safe
ฟังก์ชันแปลง Case ที่เกี่ยวข้อง
| ฟังก์ชัน | Header | คำอธิบาย |
|---|---|---|
toupper() | ctype.h | แปลงเป็น Uppercase |
tolower() | ctype.h | แปลงเป็น Lowercase |
_toupper() | ctype.h | Fast Version (UB ถ้าไม่ใช่ Lowercase) |
_tolower() | ctype.h | Fast Version (UB ถ้าไม่ใช่ Uppercase) |