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

在C++中,将字符转换为大写或小写通常使用标准库中的函数。最常用的是 toupper 和 tolower 函数,它们定义在 <cctype> 头文件中。这些函数处理单个字符,适合用于字符串中每个字符的逐个转换。
toupper 将小写字母转换为大写,tolower 将大写字母转换为小写。如果输入字符不是字母,函数会原样返回。
示例代码:
#include <iostream><br>#include <cctype><br>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 <iostream><br>#include <cctype><br>#include <string><br>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;
}
C++ 提供了 std::transform 算法,可以更简洁地实现字符串大小写转换,需包含 <algorithm> 头文件。
示例:
#include <iostream><br>#include <cctype><br>#include <string><br>#include <algorithm><br>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;
}
基本上就这些。只要记住包含 <cctype>,使用 toupper 和 tolower 处理字符,配合循环或 transform 就能灵活完成大小写转换。注意不要对非字符类型调用这些函数,避免未定义行为。
以上就是c++++中如何将字符转换为大写或小写_c++字符大小写转换方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号