| 功能 | 函數 | 頭文件 | 備註 |
|---|---|---|---|
| 判斷小寫 | islower(c) | <cctype> | 返回非零=真 |
| 判斷大寫 | isupper(c) | <cctype> | |
| 小寫→大寫 | toupper(c) | <cctype> | 非字母原樣返回 |
| 大寫→小寫 | tolower(c) | <cctype> |
#include
#include
char str[100];
scanf("%s", str);
for (int i = 0; str[i]; ++i) {
if (islower(str[i])) str[i] = toupper(str[i]);
else if (isupper(str[i])) str[i] = tolower(str[i]);
}
printf("%s\n", str);
int,但值必須是 unsigned char 或 EOF。若 `char` 為有符號類型,負值會導致未定義行為!// C++11 locale 感知
#include
std::locale loc;
for (char& c : str) c = std::toupper(c, loc);
// 標準算法
#include
std::transform(str, str+len, str, ::toupper); // 全大寫
std::transform(str, str+len, str, [](char c){ return std::islower(c) ? std::toupper(c) : std::tolower(c); }); // 大小寫互換
#include
#include
#include
#define MAXN 21
using namespace std;
char str[MAXN];
int main() {
cin >> str;
for (int i = 0; i < strlen(str); ++i) {
if (islower((unsigned char)str[i]))
str[i] = toupper((unsigned char)str[i]);
else if (isupper((unsigned char)str[i]))
str[i] = tolower((unsigned char)str[i]);
}
cout << str << endl;
return 0;
}
// 僅適用 ASCII 字符集
if ('a' <= c && c <= 'z') c = c - 'a' + 'A';
else if ('A' <= c && c <= 'Z') c = c - 'A' + 'a';
// 或位運算:c ^= 32 (僅字母有效)
注意:非 ASCII 環境(EBCDIC 等)下位運算失效,標準庫函數可移植。