将 NSString 转换为 char 数组

Convert NSString into char array(将 NSString 转换为 char 数组)
本文介绍了将 NSString 转换为 char 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 char[] 类型的变量,我想在其中复制 NSString 值.如何将 NSString 转换为 char 数组?

I have a variable of type char[] and I want to copy NSString value in it. How can I convert an NSString to a char array?

推荐答案

使用-[NSString UTF8String]:

NSString *s = @"Some string";
const char *c = [s UTF8String];

您也可以使用 -[NSString cStringUsingEncoding:] 如果你的字符串是用非 UTF-8 编码的.

You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.

一旦你有了 const char *,你就可以像使用 chars 数组一样使用它:

Once you have the const char *, you can work with it similarly to an array of chars:

printf("%c
", c[5]);

如果要修改字符串,请复制:

If you want to modify the string, make a copy:

char *cpy = calloc([s length]+1, 1);
strncpy(cpy, c, [s length]);
// Do stuff with cpy
free(cpy);

这篇关于将 NSString 转换为 char 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
Android Adding a button with multiline text inside MaterialButtonToggleGroup doesn#39;t work(Android在MaterialButtonToggleGroup中添加多行文本的按钮不起作用)
Switch Status Bar Text Color / setAppearanceLightStatusBars of WindowController is not working as expected(开关状态栏文本颜色/设置外观WindowController的LightStatusBars未按预期工作)