版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/80206022
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_t
和char
。如果对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 测试
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句