說在前面
最近緊急處理bug時候,想進行C++的字元串大小寫轉換,發現好像之前沒有用到過?!,順帶說一下C#的是真的友善~,其實并不是沒有,而是之前真的沒有用過,
那麼需要用了,就查查吧,實踐測試一下,有多種方法。
正文
有多種方法,
- 可以使用C語言标準庫函數toupper,tolower 以及對應的unicode版本 twoupper,twolower
- 可以使用C++标準庫中的_strlwr_s, _strupr_s 以及對應的unicode版本 _wcslwr_s, _wcsupr_s
- 可以用STL中的transform,包含在algorithm頭檔案中
// 2021/5/22
void TestStrToUpperLower1()
{
string strTest = ".jWS";
wstring wcsTest = L".jWS";
printf("%s using _strlwr_s of C++ standard lib\n.", __FUNCTION__);
_strlwr_s(const_cast<char*>(strTest.c_str()), strTest.size() + 1);
_wcslwr_s(const_cast<wchar_t*>(wcsTest.c_str()), wcsTest.size() + 1);
wprintf(L"result of to lower for wstring: %s\n", wcsTest.c_str());
printf("result of to lower for string: %s\n", strTest.c_str());
_strupr_s(const_cast<char*>(strTest.c_str()), strTest.size() + 1);
_wcsupr_s(const_cast<wchar_t*>(wcsTest.c_str()), wcsTest.size() + 1);
wprintf(L"result of to upper for wstring: %s\n", wcsTest.c_str());
printf("result of to upper for string: %s\n\n", strTest.c_str());
}
void TestStrToUpperLower2()
{
string strTest = ".jWS";
wstring wcsTest = L".jWS";
printf("%s using transform of algorithm\n.", __FUNCTION__);
transform(strTest.begin(), strTest.end(), strTest.begin(), ::tolower);
transform(wcsTest.begin(), wcsTest.end(), wcsTest.begin(), ::towlower);
wprintf(L"result of to lower for wstring: %s\n", wcsTest.c_str());
printf("result of to lower for string: %s\n", strTest.c_str());
transform(strTest.begin(), strTest.end(), strTest.begin(), ::toupper);
transform(wcsTest.begin(), wcsTest.end(), wcsTest.begin(), ::towupper);
wprintf(L"result of to upper for wstring: %s\n", wcsTest.c_str());
printf("result of to upper for string: %s\n\n", strTest.c_str());
}
輸出如下:

總結
多學多試,學以緻用,會有多巴胺分泌~