xcode下不能直接给wstring赋值么?如:std::wstring sz=L"abc123你我他"
xcode下不能直接给wstring赋值么?如:std::wstring sz=L"abc123你我他"
[最优解释]
可以的,我试过没有问题
[其他解释]
#import <Foundation/Foundation.h>
#include <string>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
std::wstring sz = L"abc123你我他";
wprintf(L"%s\n", sz.c_str());
NSLog(@"%s\n", sz.c_str());
return 0;
}
#include <string>
#import <Cocoa/Cocoa.h>
class CStringConverter {
public:
static std::wstring Ansi2Unicode(std::string szAnsi) {
NSString* szNs = [NSString stringWithCString:szAnsi.c_str()];
return Ns2Unicode(szNs);
}
static std::string Unicode2Ansi(std::wstring szUnicode) {
NSString* szNs = Unicode2Ns(szUnicode);
const char* rs = [szNs cString];
return rs;
}
static std::wstring Utf82Unicode(std::string szUtf8) {
NSString* szNs = [NSString stringWithUTF8String:szUtf8.c_str()];
return Ns2Unicode(szNs);
}
static std::string Unicode2Utf8(std::wstring szUnicode) {
NSString* szNs = Unicode2Ns(szUnicode);
return [szNs UTF8String];
}
static std::string Ansi2Utf8(std::string szAnsi) {
return Unicode2Utf8(Ansi2Unicode(szAnsi));
}
static std::string Utf82Ansi(std::string szUtf8) {
return Unicode2Ansi(Utf82Unicode(szUtf8));
}
static std::wstring Ns2Unicode(NSString* szNs) {
if(!szNs) return L""; //note: wchar_t is utf32 under mac
const char* szUtf8 = [szNs UTF8String];
setlocale(LC_ALL, "");
//calc block size to be returned
int len = mbstowcs(0, szUtf8, 0);
//malloc and fill the returned block
wchar_t* szUnicode = new wchar_t[len + 1];
mbstowcs(szUnicode, szUtf8, len);
szUnicode[len] = 0;
std::wstring rs = szUnicode;
delete[] szUnicode;
return rs;
}
//return value is autorelease, besure do not need to invoke NSString's release
static NSString* Unicode2Ns(std::wstring szUnicode) {
setlocale(LC_CTYPE, "");
//calc block size to be returned
int len = wcstombs(0, szUnicode.c_str(), 0);
//malloc and fill the returned block
char* szUtf8 = new char[len + 1];
wcstombs(szUtf8, szUnicode.c_str(), len);
szUtf8[len] = 0;
NSString* rs = [NSString stringWithUTF8String:szUtf8];
delete[] szUtf8;
return rs;
}
};
std::string szUtf8 = "abc123你我他";
std::wstring szUnicode = CStringConverter::Utf82Unicode(szUtf8);
wprintf(szUnicode.c_str());
printf("\n");
std::wstring sz = L"abc123你我他";
wprintf(sz.c_str());
printf("\n");