前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++11:基于STL对string,wstring进行大小写转换

C++11:基于STL对string,wstring进行大小写转换

作者头像
10km
发布2019-05-25 21:03:25
4.2K0
发布2019-05-25 21:03:25
举报
文章被收录于专栏:10km的专栏10km的专栏

版权声明:本文为博主原创文章,转载请注明源地址。 https://cloud.tencent.com/developer/article/1433492

C++标准库有对字符进行大小写转换的函数,但并没有提供对字符串的大小写转换函数,对C++ std::string进行字符串转换网上有很多文章了,

对于std::string,使用STL库algorithm中的transform模拟函数就可以实现,比如这篇文章:

《C++对string进行大小写转换》

代码语言:javascript
复制
#include <iostream> 
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>

using namespace std;

int main() 
{
    string src = "Hello World!";
    string dst;

    transform(src.begin(), src.end(), back_inserter(dst), ::toupper);
    cout << dst << endl;

    transform(src.begin(), src.end(), dst.begin(), ::tolower);
    cout << dst << endl;

    return 0;
 }

上面的代码调用transform函数遍历std::string的每个字符,对每个字符执行::toupper::tolower就实现了大小写转换。

然而对于宽字符集的字符串(std::wstring),上面的办法就适用了,因为::toupper::tolower函数并不能区分wchar_tchar。如果对std::wstring调用::toupper::tolower进行转换,就会把字符串中的宽字符集内容(比如中文)破坏。

这时需要用到<locale>库中的toupper,tolower模板函数来实现大小写转换。

实现代码如下,下面的模板函数(toupper,tolower)支持std::string,std::wstring类型字符串大小写转换

代码语言:javascript
复制
#pragma once
#include <algorithm>
#include <locale>
#include <string>
namespace l0km{
    template<typename E,
        typename TR = std::char_traits<E>,
        typename AL = std::allocator<E>>
    inline std::basic_string<E, TR, AL> toupper(const std::basic_string<E, TR, AL>&src) {
        auto dst = src;
        static const std::locale loc("");
        transform(src.begin(), src.end(), dst.begin(), [&](E c)->E {return std::toupper(c, loc); });
        return dst;
    }
    template<typename E,
        typename TR = std::char_traits<E>,
        typename AL = std::allocator<E>>
    inline std::basic_string<E, TR, AL> tolower(const std::basic_string<E, TR, AL>&src) {
        auto dst = src;
        // 使用当前的locale设置
        static const std::locale loc("");
        // lambda表达式负责将字符串的每个字符元素转换为小写
        // std::string的元素类型为char,std::wstring的元素类型为wchar_t
        transform(src.begin(), src.end(), dst.begin(), [&](E c)->E {return std::tolower(c, loc); });
        return dst;
    }
} /* namespace l0km */

调用示例

代码语言:javascript
复制
using namespace l0km;
int main() {
    std::wcout.imbue(std::locale(std::locale(), "", LC_CTYPE));
    std::wcout << gdface::tolower(std::wstring(L"字符串转小写TEST HELLO WORD 测试")) << std::endl;
    std::wcout << gdface::toupper(std::wstring(L"字符串转大写test hello word 测试")) << std::endl;
}

输出:

字符串转小写test hello word 测试 字符串转大写TEST HELLO WORD 测试

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年05月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 调用示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档