开发者

How to copy a wchar_t into an NSString?

开发者 https://www.devze.com 2022-12-26 01:55 出处:网络
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.

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?


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).


Following code worked for me:

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

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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消