Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน isupper() และ islower() ใน C++ และการประยุกต์ใช้

ภาพรวม

isupper() และ islower() เป็นฟังก์ชันใน C++ (header <cctype> หรือ <ctype.h>) ใช้ตรวจสอบว่า Character หรือ String มีตัวพิมพ์ใหญ่/เล็กหรือไม่

isupper() - ตรวจสอบตัวพิมพ์ใหญ่

Syntax

int isupper(int arg);

ค่าที่คืน

  • Non-zero (true) - มีตัวพิมพ์ใหญ่ (A-Z)
  • 0 (false) - ไม่มีตัวพิมพ์ใหญ่

ตัวอย่าง: แปลงตัวพิมพ์ใหญ่เป็นพิมพ์เล็ก

#include <stdio.h>
#include <ctype.h>

int main() {
    int i = 0;
    char str[] = "Test String.\n";
    char c;
    while (str[i]) {
        c = str[i];
        if (isupper(c))
            c = tolower(c);
        putchar(c);
        i++;
    }
    return 0;
}

ผลลัพธ์

test string.

islower() - ตรวจสอบตัวพิมพ์เล็ก

Syntax

int islower(int arg);

ค่าที่คืน

  • Non-zero (true) - มีตัวพิมพ์เล็ก (a-z)
  • 0 (false) - ไม่มีตัวพิมพ์เล็ก

ตัวอย่าง: แปลงตัวพิมพ์เล็กเป็นพิมพ์ใหญ่

#include <stdio.h>
#include <ctype.h>

int main() {
    int i = 0;
    char str[] = "Test String.\n";
    char c;
    while (str[i]) {
        c = str[i];
        if (islower(c))
            c = toupper(c);
        putchar(c);
        i++;
    }
    return 0;
}

ผลลัพธ์

TEST STRING.

ตัวอย่างการตรวจสอบ String

#include <iostream>
#include <cctype>
#include <string>
using namespace std;

bool hasUpper(const string& s) {
    for (char c : s) if (isupper(c)) return true;
    return false;
}

bool hasLower(const string& s) {
    for (char c : s) if (islower(c)) return true;
    return false;
}

int main() {
    string s1 = "HELLo";
    string s2 = "hello";
    string s3 = "HELLO";

    cout << s1 << ": upper=" << hasUpper(s1) << ", lower=" << hasLower(s1) << endl;
    cout << s2 << ": upper=" << hasUpper(s2) << ", lower=" << hasLower(s2) << endl;
    cout << s3 << ": upper=" << hasUpper(s3) << ", lower=" << hasLower(s3) << endl;
    return 0;
}

ผลลัพธ์

HELLo: upper=1, lower=1
hello: upper=0, lower=1
HELLO: upper=1, lower=0

คำอธิบายเพิ่มเติม

  • พารามิเตอร์เป็น int แต่ควรส่ง unsigned char หรือ EOF เท่านั้น (หลีกเลี่ยง UB กับค่าลบ)
  • พึ่งพา Locale - ตั้งค่าด้วย setlocale() สำหรับภาษาไทย/Unicode
  • Wide character versions: iswupper(), iswlower() (header <cwctype>)
  • C++17+ ใช้ std::isupper, std::islower จาก <locale> ได้

ฟังก์ชันคู่ (Conversion)

ตรวจสอบแปลงเป็น
isupper()tolower()
islower()toupper()
iswupper()towlower()
iswlower()towupper()