objective-c - 从包含\0 个字符的 char 数组创建 NSString?

标签 objective-c nsstring null char byte

我正在尝试从无符号字符数组(ASCII 编码)初始化一个简单的 NSString。问题是,数组中有一些 \0 作为分隔符。如果我使用

[[NSString alloc] initWithBytes:bytes length:length encoding:NSASCIIEncoding];

我只得到第一个 \0 之前的部分。即使有 \0,有没有办法获取长度参数中指定的字节数?

最佳答案

整个数组构成了字符串,只是当您尝试显示它时,只显示了初始 \0 之前的部分。

下面是说明这一点的代码:

unsigned char data[] = "hello\0world";
NSString *str = [[NSString alloc] initWithBytes:data length:sizeof(data) encoding:NSASCIIStringEncoding];
NSLog(@"%@", str);
NSLog(@"%@", [str substringFromIndex:6]);

这会产生以下日志输出:

hello
world

关于objective-c - 从包含\0 个字符的 char 数组创建 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923438/

相关文章:

iphone - 如果移动,UIImageView 将缩放而不是旋转,iOS

objective-c - 如何限制Objective C中枚举值的可见性?

ios - 在 NSString 中查找各种子字符串

objective-c - 本地化字符串和字符串比较

iPhone SDK : Please explain why "nil ==" is different than "== nil"

C#:在什么情况下应该清空引用?

objective-c - 如何使用 SwiftPM 在 objective-c 模块中使用 swift 模块?

ios - TableView编辑风格

ios - 返回方法在完成 block 中失败

postgresql - npgsql : Selecting a null data throws exception with error "Column is Null"