Replace characters in C string

半世苍凉 提交于 2019-12-12 02:47:06

问题


Given this C string:

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".

I cannot use NSString functions (replaceCharactersInRange/replaceOccurencesOfString, etc.) for performance reasons. 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.


回答1:


Objective-C is a just thin layer over C. If you need to work with native C strings, just go ahead and do it.

This

What is the function to replace string in C?

seems to address your problem fairly well.




回答2:


The C string returned by UTF8String is 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.

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.



来源:https://stackoverflow.com/questions/17298679/replace-characters-in-c-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!