4

I have received string from webservice which contains Unicode character. I want to convert that To plain NSString. so How can i do that?

ex: "This isn\u0092t your bike"

So how can remove unicode and replace it with its equal special symbol characted.

The output would be : "This isn't your bike"

Liam
  • 7,762
  • 4
  • 26
  • 27
darshan
  • 1,115
  • 1
  • 14
  • 29
  • You can look in to this post for solution http://stackoverflow.com/questions/1775859/how-to-convert-a-unichar-value-to-an-nsstring-in-objective-c – Srinivas Padidala Aug 23 '12 at 11:45

3 Answers3

7
char cString[] = "This isn\u2019t your bike";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result string: %@", string);

This should work.

UPDATE FOR THE COMMENT:

The unicode character specified by you is not supported in all fonts.

http://www.fileformat.info/info/unicode/char/92/fontsupport.htm

But this one does.

http://www.fileformat.info/info/unicode/char/2019/fontsupport.htm

Thats why it throws an error.

sElanthiraiyan
  • 6,000
  • 1
  • 31
  • 38
  • when i am triying to use the same code its says me error like "invalid universal character" – darshan Aug 23 '12 at 11:46
  • You were using a wrong unicode. I have updated the answer with the right unicode for apostrophe. Pls check – sElanthiraiyan Aug 23 '12 at 12:33
  • NO its not a wrong Unicode. Please check http://www.fileformat.info/info/unicode/char/92/index.htm ... – darshan Aug 23 '12 at 13:01
  • The error has nothing to do with fonts but with the C language and how it allows to form string literals. C99 specifies in 6.4.3.2: "A universal character name shall not specify a character whose short identifier is less than 00A0". – Nikolai Ruhe Jan 22 '13 at 12:28
2
NSString *final_url = [NSString stringWithFormat:url]; 

final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:120.0];    

NSURLResponse *response;
NSError *error = [[NSError alloc] init];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

SBJSON *objJSON = [SBJSON new];

NSMutableDictionary *objDataDic = [objJSON objectWithString:strResponse error:nil];
Prabhjot Singh Gogana
  • 1,408
  • 1
  • 14
  • 39
0

There is a library which does conversion https://github.com/alexaubry/HTMLString. It will convert all kind of Unicode character.

let escapedSnack = "Fish & Chips"
let snack = escapedSnack.removingHTMLEntities // "Fish & Chips" 
Piyush
  • 16
  • 2