How to copy a wchar_t into an NSString?

2020-03-07 08:06发布

问题:

I'm using stringWithFormat @"%ls" to do it and I only see the first character copied, which makes me think it's still assuming it's a single byte char.

Any ideas?

回答1:

Use initWithBytes:length:encoding. You will have to know the encoding that wchar_t uses, I believe it is UTF-32 on Apple platforms.

#if defined(__BIG_ENDIAN__)
# define WCHAR_ENCODING NSUTF32BigEndianStringEncoding
#elif defined(__LITTLE_ENDIAN__)
# define WCHAR_ENCODING NSUTF32LittleEndianStringEncoding
#endif

[[NSString alloc] initWithBytes:mystring
    length:(mylength * 4) encoding:WCHAR_ENCODING]

In general, I suggest avoid using wchar_t if at all possible because it is not very portable. In particular, how are you supposed to figure out what encoding it uses? (On Windows it's UTF-16LE or UTF-16BE, on OS X, Linux, and iOS it's UTF-32LE or UTF-32BE).



回答2:

Following code worked for me:

NSString *pStr = [NSString stringWithFormat:@"%S", GetTCHARString()];

Notice the "%S" part. That made the whole difference.



回答3:

From the Foundation Constants Reference, I think the function NSHostByteOrder() is the right way:

@import Foundation;

NSString * WCHARToString(wchar* wcharIn){
    if (NSHostByteOrder() == NS_LittleEndian){
        return [NSString stringWithCString: (char *)wcharIn encoding:NSUTF32LittleEndianStringEncoding];
    }
    else{
        return [NSString stringWithCString: (char *)wcharIn encoding:NSUTF32BigEndianStringEncoding];
    }
}
wchar_t * StringToWCHAR(NSString* stringIn)
{
    if (NSHostByteOrder() == NS_LittleEndian){
        return (wchar_t *)[stringIn cStringUsingEncoding:NSUTF32LittleEndianStringEncoding];
    }
    else{
        return (wchar_t *)[stringIn cStringUsingEncoding:NSUTF32BigEndianStringEncoding];
    }
}

Probably best to put them in an NSString category.



回答4:

For resolve this task I done this:

@interface NSString ( WCarToString )
- (NSString*) getStringFromWChar:(const wchar_t*) inStr;
@end

//////////////////////////

@implementation NSString ( WCarToString )

- (NSString*) getStringFromWChar:(const wchar_t*) inStr
{
char* str = new char[wcslen( inStr )+1];    
wcstombs(str, inStr, wcslen( inStr )+1 );   
NSString* wNSString = [NSString stringWithCString:str encoding:NSUTF8StringEncoding];   
delete [] str;
return wNSString;
}

@end