xcode 将 ASCII 编码的字符串转换为 UTF8?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11105742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:38:35  来源:igfitidea点击:

Convert a ASCII-encoded string to UTF8?

iphoneobjective-cxcode

提问by alpersenyurt

I have a string that is encoded with ASCII, But I need to convert it to a string that is encoded with UTF8. How can I do this?

我有一个用 ASCII 编码的字符串,但我需要将它转换为一个用 UTF8 编码的字符串。我怎样才能做到这一点?

回答by Richard J. Ross III

You are in luck. UTF8 is backwards compatible with ASCII?, so all you need to do is this (assuming your input is a C-string):

你很幸运。UTF8 向后兼容 ASCII吗?,所以你需要做的就是这个(假设你的输入是一个 C 字符串):

NSString *asNSString = [NSString stringWithUTF8String:myAsciiString];

回答by bames53

ASCII strings are UTF-8 strings, because ASCII is a strict subset of UTF-8. No conversion is necessary.

ASCII 字符串是 UTF-8 字符串,因为 ASCII 是 UTF-8 的严格子集。不需要转换。

NSString *myString = @"ascii string";

回答by chings228

NSData *data = [decode dataUsingEncoding:[NSString defaultCStringEncoding]];
decode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];