Hasib Samad
Hasib Samad

Reputation: 1081

Replace characters in C string

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.

Upvotes: 0

Views: 982

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

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.

Upvotes: 0

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

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.

Upvotes: 1

Related Questions