如何替换 char 数组中的 char? Xcode

How to replace a char in an an char array? Xcode

我在 Objective-C (Xcode):

中得到以下 char 数组
char *incomeMessage;


NSString *str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
incomeMessage = [str UTF8String];

NSLog(@"%c", incomeMessage[0]);
NSLog(@"%c", incomeMessage[1]);
NSLog(@"%c", incomeMessage[2]);
NSLog(@"%c", incomeMessage[3]);
NSLog(@"%c", incomeMessage[4]);
NSLog(@"%c", incomeMessage[5]);

例如,我在控制台中得到了这样的结果:

"3
 2
 6
 1
 8
 4"

现在我想将 incomeMessage[2] 中的字符替换为 4:

incomeMessage[2] = '4';

但是它给了我错误: EXC_BAD_ACCESS

你有什么想法,如何解决这个问题?

i got the following char array in Objective-C (Xcode)

你不知道,你知道的。你所拥有的只是一个指针。你没有留出任何实际的记忆;那里没有数组。

incomeMessage = [str UTF8String];

您在该行中所做的只是将指针 incomeMessage 重新指向字符串的 UTF8String。字符串的 UTF8String 是不可变的。请注意文档中的这段话:

you should copy the C string if it needs to be stored outside of the memory context in which you use this property.

所以基本上,如果你想写入 char 的数组,你的首要任务应该是 制作 一个 char 的数组。

根据 reference documentationUTF8String returns 对字符串数据的只读 (const char*) 引用。

参考文献 material 继续说明:

This C string is a pointer to a structure inside the string object, which may have a lifetime shorter than the string object and will certainly not have a longer lifetime. Therefore, you should copy the C string if it needs to be stored outside of the memory context in which you use this property.

所以我建议听从他们的建议并创建数组的副本,然后对其进行修改。

例如:http://ideone.com/mhjwZW

你可能会更幸运,比如:

NSString* str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
char* incomeMessage = malloc([str lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
strcpy(incomeMessage, [str UTF8String]);

//now you can change things    
incomeMessage[2] = '4';

//do this when you're done
free(incomeMessage);

尽管如此,您是否有任何特殊原因想要使用 C-string/character 数组而不是 NSMutableString?我想你可能会发现 replaceCharactersInRange:withString: a better approach generally. See also: stringByReplacingCharactersInRange:withString:.