【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函数,而第二种方法则是通过手动遍历字符串中的每个字符来实现。两种方法都是有效且常用的。

相关推荐
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++