0

I have a long string that contain keywords that start and end with the percent sign. E.g.:

My name is %user_username% and I live at %location_address%. You can reach me at %user_phone%.

What method would I use to extract all strings that begin and end with % and put those into an NSArray so that I can replace them with their correct text representations?

Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

2 Answers2

0

Assuming that there are no % signs inside your strings of interest (e.g "a%ab%b%c"), you could use the componentsSeparatedByString: or componentsSeparatedByCharactersInSet: to get an array of strings separated by the % sign. From there, it's pretty easy to figure out which strings in that array are between the percent signs, and which are unnecessary.

I think internally though, those methods are likely implemented as something like a loop looking for %s. Maybe they parallelize the search on big strings, or use special knowledge of the internal structure of the string to make things faster -- those are the only ways I can see to speed up the search, assuming that you're stuck with keeping it all in a % delimited string (if speed is really an issue, then the answer is probably to use an alternative representation).

Ben Pious
  • 4,765
  • 2
  • 22
  • 34
0

This is what I came up with that works:

- (NSArray *)replaceKeywords:(NSString *)keywordString {

    NSString *start =   @"%";
    NSString *end =     @"%";
    NSMutableArray* strings = [NSMutableArray arrayWithCapacity:0];

    NSRange startRange = [keywordString rangeOfString:start];

    for( ;; ) {

        if (startRange.location != NSNotFound) {

            NSRange targetRange;

            targetRange.location = startRange.location + startRange.length;
            targetRange.length = [keywordString length] - targetRange.location;

            NSRange endRange = [keywordString rangeOfString:end options:0 range:targetRange];

            if (endRange.location != NSNotFound) {

                targetRange.length = endRange.location - targetRange.location;
                [strings addObject:[keywordString substringWithRange:targetRange]];

                NSRange restOfString;

                restOfString.location = endRange.location + endRange.length;
                restOfString.length = [keywordString length] - restOfString.location;

                startRange = [keywordString rangeOfString:start options:0 range:restOfString];

            } else {
                break;
            }

        } else {
            break;
        }

    }

    return strings;

}

I slightly modified the method from Get String Between Two Other Strings in ObjC

Community
  • 1
  • 1
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412