ios 将 char * 转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10797350/
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 char * to NSString
提问by Saraswati
I want to show the char* in the UITextField
我想在 UITextField 中显示 char*
situation:
情况:
char *data;
char *name=data+6;
txtName.text=[[NSString alloc] initWithCString:name encoding:NSUTF8StringEncoding];
but I am not getting the correct value.
但我没有得到正确的价值。
回答by trojanfoe
To create an NSString
from a const char *
, simply use these methods:
要从 a 创建NSString
一个const char *
,只需使用以下方法:
Returns an autorelease
d object:
返回一个autorelease
d 对象:
[NSString stringWithUTF8String:name];
Returns a retain
d object:
返回一个retain
d 对象:
[[NSString alloc] initWithUTF8String:name];
参考。
If you are not getting the correct value, then something is wrong with the data. Add a few NSLog
calls to see what the strings contain.
如果您没有得到正确的值,则数据有问题。添加一些NSLog
调用以查看字符串包含的内容。
回答by gnasher729
What do you expect? You have an uninitalized char*. Then you add 6 to the pointer, which is already undefined behaviour. Then you try to turn a pointer pointing to any old rubbish (and you have no idea where it is pointing) to an NSString*. Nothing good can come from this.
你能指望什么?您有一个未初始化的 char*。然后将 6 添加到指针,这已经是未定义的行为。然后,您尝试将指向任何旧垃圾的指针(并且您不知道它指向何处)指向 NSString*。这不会有什么好处。
Define a char* pointing to an actual, real C string using ASCII or UTF-8 encoding. Then create an NSString like this:
使用 ASCII 或 UTF-8 编码定义一个指向实际 C 字符串的 char*。然后像这样创建一个 NSString:
char* cstring = "Try harder";
NSString* objcstring = @(cstring);
回答by lthms
You can use [NSString stringWithUTF8String: data]
.
您可以使用[NSString stringWithUTF8String: data]
.