NSString to const char * convert with Greek characters

折月煮酒 提交于 2019-12-30 14:44:14

问题


I'm trying to convert an NSString which contains a greek word to a const char. I'm trying to convert the string with UTF-8 encoding which is for greek language and when i'm logging the char out, it has junk in it. Please a little help here..

//this is the greek word 
NSString *letter = textFieldLetter.text;

//NSString to const char conversion for the sql query
const char *cLetter = (const char *)[letter cStringUsingEncoding:NSUTF8StringEncoding]; 

//this contains junk!
NSLog(@"letter: %s",cLetter);

回答1:


You don't have to use UTF8, instead use Unicode (NSUnicodeStringEncoding).

If you see the NSStringEncoding will see this options (have more):

enum {
NSWindowsCP1253StringEncoding = 13,    /* Greek */
NSUTF16StringEncoding = NSUnicodeStringEncoding,   

NSUTF16BigEndianStringEncoding = 0x90000100,          /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100,       /* NSUTF16StringEncoding encoding with explicit endianness specified */

NSUTF32StringEncoding = 0x8c000100,                   
NSUTF32BigEndianStringEncoding = 0x98000100,          /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100        /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
typedef NSUInteger NSStringEncoding;

You can see a specific Greek lenguage: NSWindowsCP1253StringEncoding

If is don't work, you can try to use other UTF16 or UTF32. But I think Unicode work for you.

-- edit

Take in mind that NSLog(@"%s",string); can not decode a unicode character. So, it will really show the mess.

To test if it work, do the conversion, and redo it. If is the same, so you don't lost data.

const char *cLetter = (const char *)[letter cStringUsingEncoding:NSUnicodeStringEncoding]; 
NSString *original = [NSString stringWithCString:cLetter encoding:NSUnicodeStringEncoding];


来源:https://stackoverflow.com/questions/10305488/nsstring-to-const-char-convert-with-greek-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!