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;
}
-------------------
以上代码输出:
a
2012-11-14 09:13:22.932 test[572:303] a
--------------------
另外无论64位,还是32位,在xcode下sizeof(wchar_t)为4,而windows下为2.
是不是mac系统的UNICODE是UTF32,而不是UTF16?
------其他解决方案--------------------
类unix的wchar_t实现都是UTF32,mac os x底层是darwin所以也是UTF32
另外不能用c_str()表示unicode,遇到0就结束了
wprintf,wcout之类的c函数似乎对unicode支持有限,不太了解
可以转成NSString输出:
std::wstring wstr = L"abc123你我他";
NSData *data = [NSData dataWithBytes:wstr.data() length:sizeof(wchar_t) * wstr.size()];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF32LittleEndianStringEncoding];
NSLog(@"str %@", str);
------其他解决方案--------------------
#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