C++如何将字符串转换为小写或大写?(代码示例)

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

C++如何将字符串转换为小写或大写?(代码示例)-第1张图片-佛山资讯网

在C++中,将字符串转换为小写或大写最常用的方法是遍历每个字符,调用 std::tolowerstd::toupper(需包含 <cctype></cctype>),并配合 std::string 的索引操作或迭代器。注意:这些函数作用于单个 unsigned char 值,直接传入 char 可能在负值时导致未定义行为,因此需先转换为 unsigned char

转换为小写(使用 for 循环 + tolower)

安全、清晰、兼容性好,推荐日常使用:

#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
}

登录后复制

转换为大写(使用范围 for + toupper)

更现代简洁的写法,同样注意 unsigned char 转换:

标签: ai c++ ios stream 标准库

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~