ios 将 NSString 转换为字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21870126/
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 NSString to char array
提问by NNikN
const char arr[]="Hello There";
I am trying to create a character array as above.
我正在尝试创建一个如上所述的字符数组。
Below, is the code which I use. Is this a correct way to create a char array.
下面是我使用的代码。这是创建字符数组的正确方法吗?
-(void) createCharArray:(NSString*) text{
char arr[text.length];
for(int i=0;i<text.length;i++){
arr[i]=[text characterAtIndex:i];
}
}
Do we have to worry about null termination? Do we have any other way to achieve the same?
我们是否需要担心空终止?我们还有其他方法可以实现相同的目标吗?
回答by Pranav
You can use UTF8String
. Eg: [myString UTF8String]
.
您可以使用UTF8String
. 例如:[myString UTF8String]
。
回答by Duncan C
No, that is not the correct way on several levels. NSString supports unicode, which far exceeds the number of possible characters that will fit in a byte array.
不,这在几个层面上都不是正确的方法。NSString 支持 unicode,这远远超过了适合字节数组的可能字符数。
You need to use an encoding like UTF8 if yo want to convert unicode to 8 bit characters.
如果您想将 unicode 转换为 8 位字符,您需要使用像 UTF8 这样的编码。
Take a look at the method getCString:maxLength:encoding:, and try using NSUTF8StringEncoding.
查看方法 getCString:maxLength:encoding:,并尝试使用 NSUTF8StringEncoding。
That method should do what you want to do with a single call.
该方法应该可以通过一次调用完成您想要做的事情。
回答by Akhilrajtr
Use,
用,
NSString *str = @"Hello There";
const char *c = [str cStringUsingEncoding:NSUTF8StringEncoding];