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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

10km

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值