The C + + standard library has a function that converts characters to uppercase and lowercase, but does not provide a case conversion function on a string, a string conversion to C + + std::string There are many articles on the web,
For std::string, using the Transform simulation function in the STL library algorithm can be implemented, such as this article:
C + + case Conversion of 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;
}
The code above calls the transform function to traverse each character of the std::string and perform the case conversion for each character:: ToUpper or:: ToLower.
However, for strings with wide character sets (std::wstring), the above method applies because:: ToUpper or:: The ToLower function does not distinguish between wchar_t and char. If you call Std::wstring:: ToUpper or:: ToLower to convert, the wide character set content in the string, such as Chinese, is destroyed.
You need to use the Toupper,tolower template function in the <locale> library to implement case conversion. The
Implementation code is as follows, and the following template function (Toupper,tolower) supports std::string,std::wstring type string capitalization conversions
#pragma once #include <algorithm> #include <locale> #include <string> namespace l0km{template<ty Pename E, typename TR = Std::char_traits<e>, typename AL = std::allocator<e>> Inline St
D::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 (), [Ampersand] (E c)->e {return std::toupper (c, loc);});
return DST; Template<typename E, typename TR = Std::char_traits<e>, typename AL = STD::ALLOCATOR<E&G t;> inline std::basic_string<e, tr, al> tolower (const std::basic_string<e, TR, al>&src) {A
UTO DST = src;
Use the current locale to set the static const Std::locale LOC (""); A lambda expression is responsible for converting each character element of a string to a lowercase//std::string element type of char,std::wstring with an element type of wchar_t transform (Src.begin (), S Rc.end (), Dst.begin (), [Ampersand] (E c)->e {return std::tolower (c, loc);});
return DST; }/* Namespace l0km * *
Call Example
using namespace l0km;
int main () {
Std::wcout.imbue (Std::locale (Std::locale (), "", Lc_ctype));
Std::wcout << gdface::tolower (std::wstring (L "string to lowercase test HELLO WORD tests")) << Std::endl;
Std::wcout << Gdface::toupper (std::wstring (L "string capitalization test Hello Word test)" << Std::endl;
}
Output:
String to lowercase test Hello word tests
String capitalization test HELLO WORD tests