我正在从服务器返回 UTF-8 (hex): Hc3b8rt 而不是字符串“Hørt”。我需要将此响应转换为常规 UTF-8。
我试过的:
NSString *string = [dict objectForKey:@"suggest"];
const char *cfilename=[string UTF8String];
NSString *str = [NSString stringWithUTF8String:cfilename];
感谢您的时间!
我正在从服务器返回 UTF-8 (hex): Hc3b8rt 而不是字符串“Hørt”。我需要将此响应转换为常规 UTF-8。
我试过的:
NSString *string = [dict objectForKey:@"suggest"];
const char *cfilename=[string UTF8String];
NSString *str = [NSString stringWithUTF8String:cfilename];
感谢您的时间!
使用字符串编码,NSISOLatin1StringEncoding
- (id)initWithCString:(const char *)nullTerminatedCString
encoding:(NSStringEncoding)encoding
或者很快,
NSString *str = [NSString stringWithCString:cfilename
encoding:NSISOLatin1StringEncoding];
评论后编辑:
这有点奇怪。在您发表评论后,我做了一些实验,发现了一些奇怪的行为。
- (void) testStringEncodingOK {
NSString *string = @"h\u00c3\u00a5r";
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(@"String: %@", cs);
}
这个输出:hår
但是如果你得到大写的\U,而不是\u,那么我将它们替换为\u。然后它没有用。看来,
- (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);
}
输出是,h\u00c3\u00a5r
你没有办法解码这个。正如@JoachimIsaksson 在上面的评论中所说,你怎么知道“abba”是“abba”还是两个 unicode 字符?
使用下面的代码..
const char *ch = [yourstring cStringUsingEncoding:NSISOLatin1StringEncoding];
yourstring = [[NSString alloc]initWithCString:ch encoding:NSUTF8StringEncoding];
NSLog(@"%@",yourstring);
让我知道它是否有效...
快乐的编码......
使用此代码
NSString *string = [dict objectForKey:@"suggest"];
const char *cfilename=[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *str = [NSString stringWithUTF8String:cfilename];
并告诉它是否工作。