【C++】C++实现字符串大小写转换功能

在C++中,实现字符串大小写转换可以通过标准库中的函数来完成。以下是两种常见的方法:

使用标准库函数std::transform

std::transform是一个泛型算法,可以用来对序列中的每个元素应用一个给定的函数,并把结果存储到另一个序列中。这里我们可以使用tolowertoupper函数来转换字符的大小写。

cpp 复制代码
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

std::string toLowerCase(const std::string& str) {
    std::string lowerCaseStr = str;
    std::transform(lowerCaseStr.begin(), lowerCaseStr.end(), lowerCaseStr.begin(),
                   [](unsigned char c){ return std::tolower(c); });
    return lowerCaseStr;
}

std::string toUpperCase(const std::string& str) {
    std::string upperCaseStr = str;
    std::transform(upperCaseStr.begin(), upperCaseStr.end(), upperCaseStr.begin(),
                   [](unsigned char c){ return std::toupper(c); });
    return upperCaseStr;
}

int main() {
    std::string original = "Hello World!";
    std::string lower = toLowerCase(original);
    std::string upper = toUpperCase(original);

    std::cout << "Original: " << original << std::endl;
    std::cout << "Lower Case: " << lower << std::endl;
    std::cout << "Upper Case: " << upper << std::endl;

    return 0;
}

使用循环遍历字符串

如果你不想使用std::transform,也可以通过遍历字符串中的每个字符,并使用tolowertoupper函数来转换。

cpp 复制代码
#include <iostream>
#include <string>
#include <cctype>

std::string toLowerCase(const std::string& str) {
    std::string lowerCaseStr;
    for (char c : str) {
        lowerCaseStr += std::tolower(c);
    }
    return lowerCaseStr;
}

std::string toUpperCase(const std::string& str) {
    std::string upperCaseStr;
    for (char c : str) {
        upperCaseStr += std::toupper(c);
    }
    return upperCaseStr;
}

int main() {
    std::string original = "Hello World!";
    std::string lower = toLowerCase(original);
    std::string upper = toUpperCase(original);

    std::cout << "Original: " << original << std::endl;
    std::cout << "Lower Case: " << lower << std::endl;
    std::cout << "Upper Case: " << upper << std::endl;

    return 0;
}

这两种方法都可以实现字符串的大小写转换。第一种方法使用了标准库的std::transform函数,而第二种方法则是通过手动遍历字符串中的每个字符来实现。两种方法都是有效且常用的。

相关推荐
l1t1 小时前
DeepSeek 4.1总结的Tom Lane 谈塑造 Postgres 三十年历程的架构决策
开发语言·数据库·postgresql·架构
djarmy7 小时前
MAIN.c(1): warning C318: can’t open file ‘STC8G.H’ 报错 解决 分析
c语言·开发语言·mongodb
HEJOO97 小时前
深入理解 Java volatile 关键字:原理、用法与常见误区
java·开发语言·spring
曹牧7 小时前
Java:no content to map due to end of input
java·开发语言
梦梦代码精7 小时前
《回收租赁系统技术选型避坑指南:业务闭环与二开自由度详解》
开发语言·低代码·docker·开源·代码规范
隔窗听雨眠8 小时前
记一次SQL Server数据库性能分析:从CPU100%到单配置修复的完整诊断
开发语言·数据库·php
David猪大卫8 小时前
【C++修炼】智能指针使用及原理
开发语言·c++·经验分享·笔记·学习·考研·面试
charlie1145141918 小时前
现代Qt开发之图像处理进阶:像素操作与格式转换
开发语言·图像处理·qt
李永奉8 小时前
中科蓝讯SDK开发-BT893x 面条耳机连接vivo手机后连接APP端,最后手机端设置页面手动断开蓝牙连接,此时耳机端假断开
c语言·开发语言·嵌入式硬件·物联网·智能手机·电脑
零衣贰8 小时前
The 2026 ICPC Asia East Continent Online Contest (I) 题解
c++·icpc