Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change NSString encoding

I have an NSString that looks like this.

Citroën

Which is ASCII for Citron. So in an effort to try and convert this NSString to its correct form like this

string = [dict valueForKey:@"WIGMIGDIGFIG"]; //myBadString
NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
//sent it back to NSData with ACII encoding
NSString* mystring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// put it back into a NSString but with the correct encoding
NSLog(@"%@", mystring);// check result.

So I run this through a loop to check all of the strings I have in my array of dictionaries and every single one comes back in the log accept the one string that has Citroën in it. It's just left out of the log.

Updated question, does anyone know how to do what I am trying to do? I'm not even sure whether it's possible. All I want to do is fix the string that's already created, but obviously incorrectly encoded.

like image 447
HurkNburkS Avatar asked Sep 03 '26 08:09

HurkNburkS


1 Answers

I've just tried your example and the problem is with the line:

NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];

If I NSLog the contents of data I get nil returned. This presumably means that "Citroën" is not a valid ASCII string to begin with. If I use NSUTF8StringEncoding instead I get data in the data object.

My understanding is that the string conversion methods will return nil if the string isn't able to be converted using the specified string encoding.

like image 67
mttrb Avatar answered Sep 05 '26 23:09

mttrb



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!