Ekra
Ekra

Reputation: 3301

Encode and Decode using UTF-8 in iPhone

I'm looking for an example demonstrating how I can encode and then decode the same string using UTF-8. Encode and then Decode means I want to implement the methods in 2 areas where one can encode it and another is able to decode it.

I have seen the API but I didn't get much success:


EDITED
I have the string øæ-test-2.txt which I am encoding as follows:

char *s = "øæ-test-2.txt";
NSString *enc = [NSString stringWithCString:s encoding:NSASCIIStringEncoding];

but am getting øæ-test-2.txt as output. Now I want to get back the original string back i.e. øæ-test-2.txt


EDITED
I am getting øæ-test-2.txt from server and I need øæ-test-2.txt by decoding it. I am able to get the output from the link : http://www.cafewebmaster.com/online_tools/utf_decode

Please try to use the link and you will understand my concern.

It would be highly appreciated if anyone can give some hint, tutorial or point me in the right direction.

Regards

Upvotes: 3

Views: 14725

Answers (2)

Michael
Michael

Reputation: 3259

Instead of

char *utf8string = [@"A string with ümläuts" UTF8String];

This should be

const char *utf8string = [@"A string with ümläuts" UTF8String];

Otherwise you have an incompatible type issue.

Upvotes: 2

vicvicvic
vicvicvic

Reputation: 6244

To turn an NSString object into a UTF8 C-string, use UTF8String

char *utf8string = [@"A string with ümläuts" UTF8String];

To turn a UTF8 C-string into an NSString object, use stringWithUTF8String: or initWithUTF8String:

NSString *string = [NSString stringWithUTF8String:utf8string];

Note that NSString objects are implemented as UTF-16, so you can't really have a "UTF-8 NSString" (and the encoding should be treated as an implementation detail, anyway).

Upvotes: 7

Related Questions