- 1. 關鍵詞
- 2. strutil.h
- 3. strutil.cpp
- 4. 測試代碼
- 5. 運行結果
- 6. 源碼地址
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。