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

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

对于std::string,使用STL库algorithm中的transform模拟函数就可以实现,比如这篇文章:
《C++对string进行大小写转换》

#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类型字符串大小写转换

#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 */

调用示例

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 测试

猜你喜欢

转载自blog.csdn.net/10km/article/details/80206022
今日推荐