stringWithFormat and %S problem
Here is my code.
std::wstring sourceString = L"test\n newline.";
NSString* transformedString = [NSString stringWithFormat:@"%S", sourceString.c_str()];
I intended two strings' contents to be same but transformedString is equiva开发者_StackOverflow中文版lent to @"t". How can I fix this with minimal edit?
(I have to use wstring because of unicode issue.)
On Mac OS X/iOS, wchar_t is 32 bits wide (i.e. it represents UTF-32 characters, not UTF-16 characters.) %S corresponds to a null-terminated unichar array, and unichar is 16 bits wide, not 32 bits wide, so the character 't' appears to NSString to have a trailing null character (or leading null character on Big Endian targets) causing the string to be truncated.
To convert to an NSString, try:
NSString * transformedString = [[NSString alloc]
initWithBytes: sourceString.c_str()
length: sourceString.size() * sizeof(wchar_t)
encoding: NSUTF32StringEncoding];
Note that the above assumes that wchar_t holds a UTF-32 value, which is true on Mac OS X and most (all?) *NIXes, but false on Windows (where wchar_t is 16 bits, equivalent to unichar.)
加载中,请稍侯......
精彩评论