1. 关键词
C++ 字符串处理 将字符串转成大写或小写 跨平台
2. strutil.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <string> namespace cutl {
std::string to_upper(const std::string &str);
std::string to_lower(const std::string &str); }
|
3. strutil.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <cctype> #include <algorithm> #include "strutil.h"
namespace cutl { std::string to_upper(const std::string &str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), ::toupper); return result; }
std::string to_lower(const std::string &str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), ::tolower); return result; } }
|
4. 测试代码
1 2 3 4 5 6 7 8 9 10 11 12
| #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. 运行结果
1 2 3
| -------------------------------------------TestUpperLower------------------------------------------- [to_upper] str1, before: Hello, world!, after: HELLO, WORLD! [to_lower] str2, before: GOODBYE, WORLD!, after: goodbye, world!
|
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。