Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a wstring to a NSString

I tried [NSString stringWithUTF8String:(const char*)(myWString.c_str())] but that returns a single character string.

This is on the iPhone by the way, if that matters any :)

like image 544
Harald Maassen Avatar asked Aug 31 '26 17:08

Harald Maassen


1 Answers

Within the Apple compiler the size of wchar_t is 4 bytes, so std::wstring are encoded in UTF32 and not in UTF16 as in Microsoft and other compilers.

std::wstring sCpp = L"hello";
NSString * sObjC = [[NSString alloc] initWithBytes:sCpp.data()
                                            length:sCpp.size() * sizeof(wchar_t)
                                          encoding:NSUTF32LittleEndianStringEncoding];
like image 71
Fabio Carignano Avatar answered Sep 02 '26 07:09

Fabio Carignano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!