🅰️
【C++】アルファベットの大文字小文字の変換・反転
本記事では,C++における半角アルファベットの大文字小文字の変換方法についてまとめる.
0. 概要
大文字に変換
// #include <cctype>
char c = 'a';
c = std::toupper(c); // 'A'
小文字に変換
// #include <cctype>
char c = 'A';
c = std::tolower(c); // 'a'
大文字小文字の反転
// #include <cctype>
char c = 'a';
if(std::isalpha(c)) c ^= 0x20; // 'A'
char d = 'A';
if(std::isalpha(d)) d ^= 0x20; // 'a'
1. 前提知識
C++において,半角のアルファベットは,ASCIIコード表に沿って1Byteの数値(char型)で表現される.
そして,各アルファベットの大文字小文字の値は,6番目のビット (32, 0x20) のみが異なるよう上手く設計されている.つまり,このビットを操作すれば大文字小文字を切り替えることができる.
(↓6番目のビットについて,大文字の場合は 0
,小文字の場合は 1
になっている.)
大文字 | 大文字の値 | 小文字 | 小文字の値 |
---|---|---|---|
A | 01000001 (0x41) | a | 01100001 (0x61) |
B | 01000010 (0x42) | b | 01100010 (0x62) |
C | 01000011 (0x43) | c | 01100011 (0x63) |
... | ... | ... | ... |
X | 01010110 (0x58) | x | 01110110 (0x78) |
Y | 01010111 (0x59) | y | 01110111 (0x79) |
Z | 01011000 (0x5a) | z | 01111000 (0x7a) |
2. 実装
大文字に一括変換
6番目のビットを 0
にし,任意のアルファベットを大文字に変換する.
#include <iostream>
#include <string>
int main() {
std::string s = "HelloWorld";
for(auto &c : s) {
c &= ~0x20;
}
std::cout << s << std::endl; // HELLOWORLD
}
ただし,上記の実装方法ではアルファベット以外の文字の場合にも変換処理を行う.そのため,if文で小文字判定してから変換するか,std::toupper()
を用いた方が無難である.
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
for(auto &c : s) {
// if('a' <= c and c <= 'z') c -= 0x20;
// if(std::islower(c)) c -= 0x20;
// if(std::isalpha(c)) c &= ~0x20;
c = std::toupper(c);
}
std::cout << s << std::endl; // HELLO, WORLD!
}
小文字に一括変換
6番目のビットを 1
にし,任意のアルファベットを小文字に変換する.
#include <iostream>
#include <string>
int main() {
std::string s = "HelloWorld";
for(auto &c : s) {
c |= 0x20;
}
std::cout << s << std::endl; // helloworld
}
ただし,こちらも同様,if文で大文字判定してから変換するか,std::tolower()
を用いた方が無難である.
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
for(auto &c : s) {
// if('A' <= c and c <= 'Z') c += 0x20;
// if(std::isupper(c)) c += 0x20;
// if(std::isalpha(c)) c |= 0x20;
c = std::tolower(c);
}
std::cout << s << std::endl; // hello, world!
}
大文字小文字の反転
xor演算子を用いて6番目のビットを反転し,大文字の場合は小文字に,小文字の場合は大文字に切り替える.
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
for(auto &c : s) {
if(std::isalpha(c)) c ^= 0x20;
}
std::cout << s << std::endl; // hELLO, wORLD!
}
以上.
Discussion