2026-10-17 21:34:06
在C++中,将字符串中的所有字母转换为大写或小写可通过std::transform算法配合std::toupper或std::tolower实现,需包含<algorithm>和<cctype>头文件。以下是具体方法及示例:
1. 转换为大写(Uppercase)使用std::transform遍历字符串,将每个字符通过::toupper转换为大写:
#include <algorithm>#include <string>#include <cctype>std::string str = "Hello World!";std::transform(str.begin(), str.end(), str.begin(), ::toupper);// 结果: "HELLO WORLD!"2. 转换为小写(Lowercase)同理,使用::tolower实现转小写:
#include <algorithm>#include <string>#include <cctype>std::string str = "Hello World!";std::transform(str.begin(), str.end(), str.begin(), ::tolower);// 结果: "hello world!"3. 关键注意事项输出结果:
Original: C++ is FUN! 123Uppercase: C++ IS FUN! 123Lowercase: c++ is fun! 1235. 方法优势与适用场景为什么用::toupper而非std::toupper?C++标准库中的std::toupper可能因重载或模板导致歧义,而::toupper直接调用C风格函数,避免命名冲突。若确定无冲突,也可使用std::toupper。
如何处理Unicode字符?上述方法仅适用于ASCII字符。对于Unicode(如UTF-8),需使用第三方库(如ICU)或C++20的<locale>功能。
通过上述方法,可快速实现字符串大小写转换,满足大多数场景需求。