String comparison. How can you compare string with std :: wstring? WRT strcmp

I am trying to compare two formats that I expected would be somewhat compatible, as they are both strings. I tried to execute strcmp with a string and std :: wstring, and as I am sure, C ++ gurus know this just won't compile. Can these two types be compared? Is there an easy conversion here?

+5
source share
4 answers

You need to convert the string char*- "multibyte" in ISO C - to the string wchar_t*- "wide character" in ISO C. The standard function that does this is called mbstowcs("Multibyte string for wide character string")

: , C99 , , ISO ++, ++ . MSVC g++ .

:

const char* input = ...;

std::size_t output_size = std::mbstowcs(NULL, input, 0); // get length
std::vector<wchar_t> output_buffer(output_size);

// output_size is guaranteed to be >0 because of \0 at end
std::mbstowcs(&output_buffer[0], input, output_size);

std::wstring output(&output_buffer[0]);

wstring s, , . , ( Windows ANSI) - , , , , - iconv.

, -, (.. (wchar_t)c char c ). , , , , char - ASCII Latin-1, wchar_t - Unicode. , , - std::lexicographical_compare:

#include <algorithm>

const char* s = ...;
std::wstring ws = ...;

const char* s_end = s + strlen(s);

bool is_ws_less_than_s = std::lexicographical_compare(ws.begin, ws.end(),
                                                      s, s_end());
bool is_s_less_than_ws = std::lexicographical_compare(s, s_end(),
                                                      ws.begin(), ws.end());
bool is_s_equal_to_ws = !is_ws_less_than_s && !is_s_less_than_ws;

, std::equal :

#include <algorithm>

const char* s = ...;
std::wstring ws = ...;

std::size_t s_len = strlen(s);
bool are_equal =
    ws.length() == s_len &&
    std::equal(ws.begin(), ws.end(), s);
+9

wstring .

wstring a = L"foobar";
string  b(a.begin(),a.end());

char *, b.c_str() , .

char c[] = "foobar";
cout<<strcmp(b.c_str(),c)<<endl;
+2

, , std:: wstring, unicode char * (cstring), ansi. , , . , cstrings unicode, wchar_t. , STL- ansi, std::string.

.

, , .

std::string a std::wstring c_str

const char* std::string::c_str() const
const wchar_t* std::wstring::c_str() const

, char * wchar_t * , strcmp. google, .

std:: wstring std::string, c_str char *, strcmp

#include <string>
#include <algorithm>

// Prototype for conversion functions
std::wstring StringToWString(const std::string& s);
std::string WStringToString(const std::wstring& s);

std::wstring StringToWString(const std::string& s)
{
std::wstring temp(s.length(),L' ');
std::copy(s.begin(), s.end(), temp.begin());
return temp; 
}


std::string WStringToString(const std::wstring& s)
{
std::string temp(s.length(), ' ');
std::copy(s.begin(), s.end(), temp.begin());
return temp; 
}
+2

if( std::wstring(your_char_ptr_string) == your_wstring)

"", . , , .

, wstring 16- (, unicode - 65536 ), char * 8- ( Ascii, ). , wstring → char * .

-Tom

+2
source

All Articles