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。