推荐使用for循环配合std::tolower(需先转unsigned char)转换字符串为小写,安全清晰兼容性好。

在C++中,将字符串转换为小写或大写最常用的方法是遍历每个字符,调用 std::tolower 或 std::toupper(需包含 <cctype></cctype>),并配合 std::string 的索引操作或迭代器。注意:这些函数作用于单个 unsigned char 值,直接传入 char 可能在负值时导致未定义行为,因此需先转换为 unsigned char。
安全、清晰、兼容性好,推荐日常使用:
#include <iostream>
#include <string>
#include <cctype> // tolower, toupper
std::string toLower(const std::string& s) {
std::string result = s;
for (size_t i = 0; i < result.length(); ++i) {
result[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(result[i])));
}
return result;
}
// 使用示例
int main() {
std::string s = "Hello World! 123";
std::cout << toLower(s) << "\n"; // 输出: hello world! 123
}更现代简洁的写法,同样注意 unsigned char 转换:
std::string toUpper(std::string s) { // 传值避免修改原串
for (char& c : s) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
return s;
}如果允许修改原字符串,可省去拷贝,提升效率:
立即学习“C++免费学习笔记(深入)”;
std::string 对象调用非 const 迭代器或下标for (char& c : myStr) c = std::toupper(...)
std::tolower/toupper 依赖当前 C locale,默认只对 ASCII 字母有效;中文、Unicode 字符需用 ICU 或 std::locale(C++11+)等高级方案std::tolower(c)(其中 c 是 char),必须先转 unsigned char,否则 char 为负时行为未定义std::string::to_lower() 成员函数,切勿误用以上就是C++如何将字符串转换为小写或大写?(代码示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号