可以通过标准库中的 <algorithm><cctype> 头文件来实现大小写转换。以下是常用的方法:


1. 使用 std::transformstd::toupper/std::tolower

1.1 转换为大写

#include <iostream>
#include <string>
#include <algorithm> // std::transform
#include <cctype>    // std::toupper

int main() {
    std::string s = "Hello, World!";

    // 转换为大写
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);

    std::cout << "Uppercase: " << s << std::endl; // HELLO, WORLD!

    return 0;
}

1.2 转换为小写

#include <iostream>
#include <string>
#include <algorithm> // std::transform
#include <cctype>    // std::tolower

int main() {
    std::string s = "Hello, World!";

    // 转换为小写
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);

    std::cout << "Lowercase: " << s << std::endl; // hello, world!

    return 0;
}

2. 手动实现大小写转换

2.1 转换为大写

#include <iostream>
#include <string>
#include <cctype> // std::toupper

int main() {
    std::string s = "Hello, World!";

    for (char& c : s) {
        c = std::toupper(c);
    }

    std::cout << "Uppercase: " << s << std::endl; // HELLO, WORLD!

    return 0;
}

2.2 转换为小写

#include <iostream>
#include <string>
#include <cctype> // std::tolower

int main() {
    std::string s = "Hello, World!";

    for (char& c : s) {
        c = std::tolower(c);
    }

    std::cout << "Lowercase: " << s << std::endl; // hello, world!

    return 0;
}

3. 处理非 ASCII 字符(如中文)

std::toupperstd::tolower 只能处理 ASCII 字符。如果需要处理 Unicode 字符(如中文),可以使用第三方库(如 ICU 或 Boost)。


4. 示例:选择性转换

如果只需要转换部分字符,可以通过条件判断实现。

#include <iostream>
#include <string>
#include <cctype> // std::tolower, std::toupper

int main() {
    std::string s = "Hello, World!";

    // 只转换字母
    for (char& c : s) {
        if (std::isalpha(c)) {
            c = std::tolower(c);
        }
    }

    std::cout << "Selective lowercase: " << s << std::endl; // hello, world!

    return 0;
}

5. 注意事项

  • std::toupperstd::tolower 的参数和返回值是 int 类型,需要强制转换为 char
  • 如果字符串中包含非 ASCII 字符(如中文),std::toupperstd::tolower 可能无法正确处理。
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐