使用toupper和tolower可转换字符大小写,通过循环或transform可处理整个字符串,需包含和头文件。

在C++中,将字符转换为大写或小写通常使用标准库中的函数。最常用的是 toupper 和 tolower 函数,它们定义在
使用 toupper 和 tolower 转换单个字符
toupper 将小写字母转换为大写,tolower 将大写字母转换为小写。如果输入字符不是字母,函数会原样返回。
示例代码:
#include
#include
using namespace std; int main() { char ch1 = 'a'; char ch2 = 'B'; cout << toupper(ch1) << endl; // 输出: A cout << tolower(ch2) << endl; // 输出: b return 0; }
转换整个字符串的大小写
要转换字符串中所有字符的大小写,可以结合 std::string 和循环或标准算法。
立即学习“C++免费学习笔记(深入)”;
使用 for 循环 示例:
#include
#include
#include
using namespace std; int main() { string str = "Hello World"; // 转换为大写 for (char &c : str) { c = toupper(c); } cout << str << endl; // 输出: HELLO WORLD // 转换为小写 for (char &c : str) { c = tolower(c); } cout << str << endl; // 输出: hello world return 0; }
使用 transform 算法进行转换
C++ 提供了 std::transform 算法,可以更简洁地实现字符串大小写转换,需包含
示例:
#include
#include
#include
#include
using namespace std; int main() { string str = "C++ Programming"; // 转为大写 transform(str.begin(), str.end(), str.begin(), ::toupper); cout << str << endl; // 输出: C++ PROGRAMMING // 转为小写 transform(str.begin(), str.end(), str.begin(), ::tolower); cout << str << endl; // 输出: c++ programming return 0; }
基本上就这些。只要记住包含











