Compare std::wstring and std::string

前端 未结 3 599
青春惊慌失措
青春惊慌失措 2020-11-29 09:10

How can I compare a wstring, such as L\"Hello\", to a string? If I need to have the same type, how can I convert them into the same ty

3条回答
  •  感情败类
    2020-11-29 09:35

    Think twice before doing this — you might not want to compare them in the first place. If you are sure you do and you are using Windows, then convert string to wstring with MultiByteToWideChar, then compare with CompareStringEx.

    If you are not using Windows, then the analogous functions are mbstowcs and wcscmp. The standard wide character C++ functions are often not portable under Windows; for instance mbstowcs is deprecated.

    The cross-platform way to work with Unicode is to use the ICU library.

    Take care to use special functions for Unicode string comparison, don't do it manually. Two Unicode strings could have different characters, yet still be the same.

    wstring ConvertToUnicode(const string & str)
    {
        UINT  codePage = CP_ACP;
        DWORD flags    = 0;
        int resultSize = MultiByteToWideChar
            ( codePage     // CodePage
            , flags        // dwFlags
            , str.c_str()  // lpMultiByteStr
            , str.length() // cbMultiByte
            , NULL         // lpWideCharStr
            , 0            // cchWideChar
            );
        vector result(resultSize + 1);
        MultiByteToWideChar
            ( codePage     // CodePage
            , flags        // dwFlags
            , str.c_str()  // lpMultiByteStr
            , str.length() // cbMultiByte
            , &result[0]   // lpWideCharStr
            , resultSize   // cchWideChar
            );
        return &result[0];
    }
    

提交回复
热议问题