Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSString encoding to UTF8

I have done something like:

NSData *dt = [mystr dataUsingEncoding:NSWindowsCP1251StringEncoding];

NSString *str = [NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];

then NSLog(@"%@", str);

However, if 'mystr' is English then the NSLog would print it as is, but if mystr is Arabic (for ex.) NSLog will not print anything, so how can I change the encoding of mystr to UTF8?

like image 420
JAHelia Avatar asked Nov 17 '25 06:11

JAHelia


1 Answers

Your first line creates some data that is in cp1251 encoding. Your second line says "read this data into a string, assuming that the bytes represent a UTF8 encoded string". But because the bytes represent a cp1251 encoded string, that's not likely to work very well.

NSString represents an ordered collection of characters. Internally it uses some encoding to store these characters in memory, but its interface provides an encoding-independent access to the string and you can therefore consider NSString to be encoding-agnostic. If what you want is a collection of bytes that represent the string in UTF8 encoding, then you don't want an NSString. You want to get an NSString to emit such a collection of bytes, perhaps using the -dataUsingEncoding: method you've already found.


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!