【C++】大文字・小文字の判定方法【簡単】

【C++】大文字・小文字の判定方法【簡単】

C++の文字型と文字コード

C++では、文字を表すために主に char 型が使用されます。ASCIIコードを基準にすると、大文字は65(’A’)から90(’Z’)、小文字は97(’a’)から122(’z’)の範囲に収まります。


#include <iostream>

int main() {
    char c = 'A';
    std::cout << "A の ASCII コード: " << static_cast(c) << std::endl;
    return 0;
}

大文字・小文字の判定方法

C++では、標準ライブラリに大文字・小文字を判定する関数が用意されています。cctype ヘッダを使用すると簡単に判定できます。

isupper を使った大文字判定


#include <iostream>
#include <cctype>

int main() {
    char c = 'G';
    if (std::isupper(c)) {
        std::cout << c << " は大文字です。" << std::endl;
    }
    return 0;
}

islower を使った小文字判定


#include <iostream>
#include <cctype>

int main() {
    char c = 'g';
    if (std::islower(c)) {
        std::cout << c << " は小文字です。" << std::endl;
    }
    return 0;
}

手動でASCIIコードを用いた判定


#include <iostream>

int main() {
    char c = 'M';
    if (c >= 'A' && c <= 'Z') {
        std::cout << c << " は大文字です。" << std::endl;
    } else if (c >= 'a' && c <= 'z') {
        std::cout << c << " は小文字です。" << std::endl;
    }
    return 0;
}

大文字・小文字の変換方法

C++では touppertolower を使用して、大文字・小文字の変換が可能です。

toupper を使った小文字 → 大文字変換


#include <iostream>
#include <cctype>

int main() {
    char c = 'b';
    char upper = std::toupper(c);
    std::cout << c << " → " << upper << std::endl;
    return 0;
}

tolower を使った大文字 → 小文字変換


#include <iostream>
#include <cctype>

int main() {
    char c = 'Z';
    char lower = std::tolower(c);
    std::cout << c << " → " << lower << std::endl;
    return 0;
}

カスタムロジックでの判定

標準関数を使わずに、ASCIIコードを活用した変換方法もあります。

小文字 → 大文字変換


#include <iostream>

int main() {
    char c = 'h';
    char upper = (c >= 'a' && c <= 'z') ? c - 32 : c;
    std::cout << c << " → " << upper << std::endl;
    return 0;
}

大文字 → 小文字変換


#include <iostream>

int main() {
    char c = 'R';
    char lower = (c >= 'A' && c <= 'Z') ? c + 32 : c;
    std::cout << c << " → " << lower << std::endl;
    return 0;
}

Unicode対応の大文字・小文字判定

C++の標準ライブラリはUTF-8の大文字・小文字変換を直接サポートしていませんが、boost::locale を利用するとUnicode対応の変換が可能になります。

Boost.Locale を使った変換


#include <iostream>
#include <boost/locale.hpp>

int main() {
    std::string str = "Äpfel";
    std::string upper = boost::locale::to_upper(str, "de_DE.UTF-8");
    std::string lower = boost::locale::to_lower(str, "de_DE.UTF-8");

    std::cout << "Original: " << str << std::endl;
    std::cout << "Uppercase: " << upper << std::endl;
    std::cout << "Lowercase: " << lower << std::endl;

    return 0;
}

Unicode対応が必要な場合は、Boost.Locale や ICU ライブラリを活用するのが一般的です。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です