简体   繁体   English

替换C字符串中的字符

[英]Replace characters in C string

Given this C string: 给定这个C字符串:

unsigned char *temp = (unsigned char *)[@"Hey, I am some usual CString" UTF8String]

How can I replace "usual" with "other" to get: "Hey, I am some other CString". 我如何用“ other”替换“ usual”以得到:“嘿,我是其他CString”。

I cannot use NSString functions ( replaceCharactersInRange / replaceOccurencesOfString , etc.) for performance reasons. 由于性能原因,我不能使用NSString函数( replaceCharactersInRange / replaceOccurencesOfString等)。 I have to keep it all at low level, since the strings I'll be dealing with happen to exceed 5MB, and therefore the replacements (there will be a lot of replacements to do) take about 10 minutes on a iOS device. 我必须将所有内容保持在较低的水平,因为要处理的字符串恰好超过5MB,因此在iOS设备上进行替换(将要进行很多替换)大约需要10分钟。

Objective-C is a just thin layer over C. If you need to work with native C strings, just go ahead and do it. Objective-C是C之上的薄薄一层。如果您需要使用本机C字符串,只需继续进行即可。

This 这个

What is the function to replace string in C? 在C中替换字符串的功能是什么?

seems to address your problem fairly well. 似乎可以很好地解决您的问题。

The C string returned by UTF8String is const. UTF8String返回的C字符串是const。 You can't safely change it by casting it to a non-const string and mutate the bytes. 您不能通过将其强制转换为非常量字符串并更改字节来安全地对其进行更改。 So the only way to do this is by creating a copy. 因此,唯一的方法就是创建一个副本。

If you really have reason to use an NSString as the source it might be much faster to do the transformation on the original string. 如果确实有理由使用NSString作为源,那么对原始字符串进行转换可能会更快。

If you want to get a better answer that helps you to speed up your special case you should provide some more information. 如果您想获得更好的答案,以帮助您加快特殊情况的发生,则应提供更多信息。 How do you create the original string, what's the number and size of search/replacement strings and so on. 您如何创建原始字符串,搜索/替换字符串的数量和大小等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM