How do I convert System::WideString to a char* and vice versa?
I have a situation wher开发者_如何学JAVAe I need to compare a char* with a WideString.
You can use the wcstombs function.
size_t wcstombs( char * mbstr, const wchar_t * wcstr, size_t max );
See WideCharToMultiByte() and MultiByteToWideChar().
To compare a System::WideString object with a char* (as the question body says you want to do), you can create a new WideString object from the pointer and then use ordinary == operator. The class has several constructors, including one for const char*.
char* foo = ...;
WideString bar = ...;
if (WideString(foo) == bar)
std::cout << "They're equal!\n";
In fact, as long as the WideString object is on the left, you don't even need the constructor call because the pointer will be converted automatically.
if (bar == foo) { ... }
To convert a WideString to a char* (as the question title says you want to do), you might consider using the AnsiString type. They're convertible between each other. To get the ordinary pointer, call the c_str method, just like you would with std::string.
WideString bar = ...;
AnsiString foo = bar;
std::cout << foo.c_str();
Not possible. Actually, you mixed two different concepts:
- Widestring implies a buffer in UTF-16 encoding.
- char* may contain anything, from UTF-8 to ASCII-only text (in which case, this is convertable only if your widestring does not contain non-ASCII characters).
Please see my answer to https://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful about how to properly handle text.
加载中,请稍侯......
精彩评论