🔁 isupper → tolower / islower → toupper を使った大小文字変換の基本【C++】
C++で文字の大文字・小文字を判定&変換する場合、
isupper
や islower
でチェックし、tolower
や toupper
で変換するのが定番です。
この記事では「大文字なら小文字へ、小文字なら大文字へ」という
文字反転処理をスマートに実装する方法を整理します。
✅ 使うライブラリ
以下のヘッダが必要です:
#include <iostream> // cin, cout など
#include <string> // string型を使う場合
#include <cctype> // isupper, islower, tolower, toupper
🎯 基本:1文字だけ変換するコード
char c;
cin >> c;
if (isupper(c)) {
c = tolower(c); // 大文字→小文字
} else if (islower(c)) {
c = toupper(c); // 小文字→大文字
}
cout << c << endl;
-
isupper(c)
:cが大文字ならtrue -
tolower(c)
:cを小文字に変換
「大文字か小文字かをチェックして、それに応じた変換を行う」というゴールデンコンビです。
🔁 応用:文字列全体を大小反転
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str;
getline(cin, str); // 1行入力
for (char& c : str) {
if (isupper(c)) c = tolower(c);
else if (islower(c)) c = toupper(c);
}
cout << str << endl;
return 0;
}
📝 入力例:
Hello World 123!
🖨️ 出力例:
hELLO wORLD 123!
🧠 応用:NGワードを大文字小文字無視で検出
大文字・小文字を区別せずに文字列を比較したいときにも使えます。
以下は、NGワードが含まれているかどうかを大小文字を無視してチェックする例です。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// 小文字に変換する関数
string toLower(const string& s) {
string result = s;
for (char& c : result) {
if (isupper(c)) c = tolower(c);
}
return result;
}
int main() {
string input, ng;
cin >> input >> ng;
string inputLower = toLower(input);
string ngLower = toLower(ng);
if (inputLower.find(ngLower) != string::npos) {
cout << "NGワードを検出しました。" << endl;
} else {
cout << "安全です。" << endl;
}
return 0;
}
✅ まとめ
条件関数 | 変換関数 | 目的 |
---|---|---|
isupper(c) |
tolower(c) |
大文字なら小文字にする |
islower(c) |
toupper(c) |
小文字なら大文字にする |
- チェックと変換はセットで覚えると便利
- 文字列全体の変換にも応用可能
- 大文字・小文字の区別を無視した比較にも使える
🎁 おまけ:全部小文字 or 大文字にするだけなら?
#include <algorithm>
#include <cctype>
// 小文字化:
transform(str.begin(), str.end(), str.begin(), ::tolower);
// 大文字化:
transform(str.begin(), str.end(), str.begin(), ::toupper);
transform
は STLの便利なアルゴリズム。
全部一括で処理したいときはこれが便利です。
こういった「is○○ → to○○」の形を覚えておくと、
ちょっとした文字処理をスッキリ書けて、PaizaのC〜B問題やAtCoderなどでも役立ちます!