2026-10-21 08:56:32
在C++中,将字符转换为大写或小写可通过以下方法实现,涵盖单字符处理和字符串整体转换的多种场景:
一、单字符转换:tolower 和 toupper 函数函数原型与头文件
定义在 <cctype> 头文件中(C语言对应 <ctype.h>)。
函数原型:int tolower(int ch); // 转换为小写int toupper(int ch); // 转换为大写
参数为 int 类型,但通常传入 char 字符;返回值为转换后的字符的ASCII码(int 类型),需强制转换为 char。
使用示例
#include <iostream>#include <cctype>using namespace std;int main() { char ch1 = 'a'; char ch2 = 'B'; // 转换为大写和小写 cout << (char)toupper(ch1) << endl; // 输出 'A' cout << (char)tolower(ch2) << endl; // 输出 'b' return 0;}注意:若传入非字母字符(如数字、符号),函数会原样返回该字符。
通过下标或范围循环(C++11起)遍历 string,使用引用直接修改原字符。
示例:字符串转大写#include <iostream>#include <cctype>#include <string>using namespace std;int main() { string str = "Hello World!"; for (char &c : str) { // 使用引用修改原字符 c = toupper(c); } cout << str << endl; // 输出 "HELLO WORLD!" return 0;}
算法原理
<algorithm> 中的 transform 可对容器(如 string)进行批量操作。
需指定输入范围、输出位置和转换函数(如 ::tolower 或 ::toupper)。
使用全局作用域符 :: 避免与可能的重载函数冲突。
示例代码
字符串转小写#include <iostream>#include <algorithm>#include <cctype>#include <string>using namespace std;int main() { string str = "C++ Programming"; // 使用 transform 转小写 transform(str.begin(), str.end(), str.begin(), ::tolower); cout << str << endl; // 输出 "c++ programming" return 0;}
字符串转大写transform(str.begin(), str.end(), str.begin(), ::toupper);
单字符转换需 <cctype>,字符串转换需 <algorithm> 和 <string>。
tolower/toupper 返回 int,输出时需强制转换为 char。
函数对非字母字符(如数字、空格)无影响,直接原样返回。
单字符转换适合简单场景;字符串转换推荐 transform,代码更简洁且安全。
遍历修改:适合需要灵活控制的场景。
transform 算法:推荐方式,代码简洁且高效。
通过以上方法,可灵活处理C++中的字符大小写转换需求。