C++ 字符串处理-将字符串转成大写或小写

1. 关键词

C++ 字符串处理 将字符串转成大写或小写 跨平台

2. strutil.h

#include <string>
namespace cutl
{
    /**
     * @brief Convert a string to upper case.
     *
     * @param str the string to be converted.
     * @return std::string the converted string.
     */
    std::string to_upper(const std::string &str);
    /**
     * @brief Convert a string to lower case.
     *
     * @param str the string to be converted.
     * @return std::string the converted string.
     */
    std::string to_lower(const std::string &str);
} // namespace cutl

3. strutil.cpp

#include <cctype>
#include <algorithm>
#include "strutil.h"

namespace cutl
{
    std::string to_upper(const std::string &str)
    {
        std::string result = str;
        // <cctype>里面声明了一个C版本的函数toupper/tolower,<local>里也声明了一个toupper/tolower的函数模板
        // 所以std命名空间下std::toupper有名称冲突,Linux下会编译失败,这里使用全局作用域的::toupper(即使用C语言的版本)
        std::transform(result.begin(), result.end(), result.begin(), ::toupper);
        return result;
    }

    std::string to_lower(const std::string &str)
    {
        std::string result = str;
        // <cctype>里面声明了一个C版本的函数toupper/tolower,<local>里也声明了一个toupper/tolower的函数模板
        // 所以std命名空间下std::tolower有名称冲突,Linux下会编译失败,这里使用全局作用域的::tolower(即使用C语言的版本)
        std::transform(result.begin(), result.end(), result.begin(), ::tolower);
        return result;
    }
} // namespace cutl

4. 测试代码

#include "common.hpp"
#include "strutil.h"

void TestUpperLower()
{
    PrintSubTitle("TestUpperLower");

    std::string str1 = "Hello, world!";
    std::string str2 = "GOODBYE, WORLD!";
    std::cout << "[to_upper] str1, before: " << str1 << ", after: " << cutl::to_upper(str1) << std::endl;
    std::cout << "[to_lower] str2, before: " << str2 << ", after: " << cutl::to_lower(str2) << std::endl;
}

5. 运行结果

-------------------------------------------TestUpperLower-------------------------------------------
[to_upper] str1, before: Hello, world!, after: HELLO, WORLD!
[to_lower] str2, before: GOODBYE, WORLD!, after: goodbye, world!

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌尘(MoChen)

爱打赏的人技术成长更开哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值