0

I am getting UTF-8 (hex): Hc3b8rt back from a server instead of the string "Hørt". I need to convert this response to regular UTF-8.

What I have tried:

NSString *string = [dict objectForKey:@"suggest"];

const char *cfilename=[string UTF8String];

NSString *str = [NSString stringWithUTF8String:cfilename];

Thank you for your time!

AlexanderN
  • 2,610
  • 1
  • 26
  • 42

4 Answers4

1

use string encoding, NSISOLatin1StringEncoding

 - (id)initWithCString:(const char *)nullTerminatedCString 
              encoding:(NSStringEncoding)encoding

Or shortly,

NSString *str = [NSString stringWithCString:cfilename 
                                   encoding:NSISOLatin1StringEncoding];

Edit after comments:

This is kind of strange. I have done some experiments after your comments and found some strange behaviour.

- (void) testStringEncodingOK {
    NSString *string = @"h\u00c3\u00a5r";
    const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
    NSString *cs = [NSString stringWithUTF8String:cfilename];
    NSLog(@"String: %@", cs);
}

This output: hår

But if you get the \U in capital, not \u, then I replaced them to \u. And then it did not work. Seem the ,

- (void) testStringEncodingConfused {
    NSString *string = @"h\\U00c3\\U00a5r";
    string = [string stringByReplacingOccurrencesOfString:@"\\U" withString:@"\\u"];
NSLog(@"Original string:%@", string); // now string = @"h\u00c3\u00a5r"
    const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
    NSString *cs = [NSString stringWithUTF8String:cfilename];
    NSLog(@"String: %@", cs);
}

The output is, h\u00c3\u00a5r

karim
  • 15,408
  • 7
  • 58
  • 96
1

There's no way you can decode this. As @JoachimIsaksson stated in the comments above, how can you tell if "abba" is exactly "abba" or two unicode chars?

0

Use below code..

  const char *ch = [yourstring cStringUsingEncoding:NSISOLatin1StringEncoding];

  yourstring = [[NSString alloc]initWithCString:ch encoding:NSUTF8StringEncoding];

   NSLog(@"%@",yourstring);

let me know it is working or not...

Happy Coding....

NiravPatel
  • 3,260
  • 2
  • 21
  • 31
  • check this answer...http://stackoverflow.com/questions/6421282/how-to-convert-hex-to-nsstring-in-objective-c....tell me working or not!!!! – NiravPatel May 27 '13 at 10:12
0

use this code

NSString *string = [dict objectForKey:@"suggest"];

const char *cfilename=[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSString *str = [NSString stringWithUTF8String:cfilename];

and tell if it is working or not.

iEinstein
  • 2,100
  • 1
  • 21
  • 32