2012-08-23 95 views
4

我從包含Unicode字符的webservice收到字符串。我想將其轉換爲普通的NSString。所以我該怎麼做?將Unicode字符轉換爲NSString

前:「這ISN \ u0092t你的自行車」

那麼,怎樣才能去除Unicode和與characted的平等特殊符號代替它。

輸出將是: 「這不是你的自行車」

+0

你可以在看這篇文章的解決方案 http://stackoverflow.com/questions/1775859/how-to-convert-a-unichar-value-to-an-nsstring-in-objective -c –

回答

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); 

這應該工作。

更新註釋:

由您指定的Unicode字符是不是在所有的字體支持。

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

但是這一次呢。

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

這就是爲什麼它拋出一個錯誤。

+0

當我試圖使用相同的代碼它說我錯誤,如「無效的通用字符」 – darshan

+0

您正在使用一個錯誤的Unicode。我用正確的撇號更新了答案。請檢查 – sElanthiraiyan

+0

不是錯誤的Unicode。請檢查http://www.fileformat.info/info/unicode/char/92/index.htm ... – darshan

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];