Search code examples
iosreplacensstringhtml-escape-characters

Is there any efficient way to replace characters in NSString


I have 20 lines of code that replaces multiple values of NSString as below.

[resultstring
    replaceOccurrencesOfString:@"&"
    withString:@"&"
    options:NSLiteralSearch
    range:NSMakeRange(0, [resultstring length])
];

The problem is that it is takes some noticeable amount of time (20ms) for executing the code. Is there any better approach to write the NSString replacement code.


Solution

  • replaceOccurrencesOfString:... will traverse the string each time you call it.

    An alternative which should make the replacement faster is to manually traverse the string just once and build a new string along the way.

    Here's an example, although there's probably still room for further optimization

    - (NSString *)encodeEntity:(NSString *)string {
        NSUInteger length = string.length;
        NSMutableString *encodedString = [NSMutableString stringWithCapacity:length];
        unichar buffer[length + 1];
        [string getCharacters:buffer range:(NSRange){0, length}];
        for(NSUInteger i = 0; i < length; i++) {
            char current = buffer[i];
            switch(current) {
                case '&':  [encodedString appendString:@"&amp;"];        break;
                case '\"': [encodedString appendString:@"&quot;"];       break;
                case '\'': [encodedString appendString:@"&apos;"];       break;
                case '<':  [encodedString appendString:@"&lt;"];         break;
                case '>':  [encodedString appendString:@"&gt;"];         break;
                default:   [encodedString appendFormat:@"%c", current];  break;
            }
        }
        return encodedString;
    }
    

    Also if your specific issue is to escape XML entities, this question may be useful: Objective C HTML escape/unescape