C++ 使用长度和编码将 const char* 字符串转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2121763/
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
Convert const char* string to NSString with length AND encoding
提问by tksohishi
I wonder which method would be better to convert const char* string to NSString.
I found there are some facts.
我想知道哪种方法会更好地将 const char* 字符串转换为 NSString。
我发现有一些事实。
- [NSString stringWithCString:length:] is kind of deprecated.
- [NSString stringWithCString:encoding] may be used for my purpose
- [NSString stringWithCString:length:] 有点过时了。
- [NSString stringWithCString:encoding] 可用于我的目的
But I want to convert with length AND encoding(because I want to make that fine if I have some Non-ASCII character by setting encoding to UTF-8). Any thoughts?
但我想用长度和编码进行转换(因为如果我有一些非 ASCII 字符,我想通过将编码设置为 UTF-8 来做到这一点)。有什么想法吗?
I just think now
我现在只想
- create other char and copy with length by using std::strncpy(ch1, ch2, len)
- use [NSString stringWithCString:encoding:]
- 使用 std::strncpy(ch1, ch2, len) 创建其他字符并复制长度
- 使用 [NSString stringWithCString:encoding:]
But it doesn't work well.
但效果不佳。
回答by Jon Reid
If your const char* variable is named foo
(and it points to a null-terminated string), just say
如果您的 const char* 变量被命名foo
(并且它指向一个以空字符结尾的字符串),只需说
[NSString stringWithUTF8String:foo]
Because UTF-8 is a superset of ASCII, this will work whether foo
points to UTF-8 or ASCII. Then you can move up to full Unicode with no problems.
因为 UTF-8 是 ASCII 的超集,所以无论foo
指向 UTF-8 还是 ASCII 都可以使用。然后,您可以毫无问题地升级到完整的 Unicode。
回答by Dietrich Epp
Use:
用:
[NSString initWithBytes:length:encoding].