使用std::transform配合std::toupper是转换字符串为大写的推荐方法,通过遍历字符或封装函数可实现小写转大写,注意使用unsigned char避免未定义行为。

在C++中,将字符串中的所有小写字母转换为大写是一个常见的操作。可以通过标准库函数或手动遍历字符实现。以下是几种常用且有效的方法。
使用 std::toupper 转换单个字符
要将小写字母转为大写,可以使用结合 std::string 和循环,可以遍历整个字符串:
#include
#include
#include
int main() {
std::string str = "hello world!";
for (char &c : str) {
c = std::toupper(c);
}
std::cout << str << std::endl; // 输出: HELLO WORLD!
return 0;
}
使用 std::transform 批量转换
更简洁的方式是使用#include注意:lambda 中使用 unsigned char 是为了避免对负值字符调用 std::toupper 时出现未定义行为。
#include
#include
#include
int main() {
std::string str = "hello c++!";
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::toupper(c); });
std::cout << str << std::endl; // 输出: HELLO C++!
return 0;
}
封装成可复用函数
为了方便重复使用,可以将转换逻辑封装成函数:std::string toUpperCase(const std::string& input) {
std::string result = input;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c){ return std::toupper(c); });
return result;
}
调用示例:
std::string original = "convert me";
std::string upper = toUpperCase(original);
std::cout << upper << std::endl; // 输出: CONVERT ME
基本上就这些。使用 std::transform 配合 std::toupper 是最推荐的做法,既高效又清晰。手动循环也容易理解,适合初学者掌握原理。不复杂但容易忽略的是字符类型的安全处理,尤其是涉及非 ASCII 字符时要注意编码问题。











