Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iphone iterate over substring occurrences of a NSString

I would like to find all occurrences of a substring in a NSString, and iterate one by one to do some changes to that NSString. How should I do it?

like image 723
Luis Andrés García Avatar asked Mar 08 '12 10:03

Luis Andrés García


3 Answers

How about

// find first occurrence of search string in source string
NSRange range = [sourceString rangeOfString:@"searchString"];
while(range.location != NSNotFound)
{
    // build a new string with your changed values

    range = [sourceString rangeOfString:@"searchString" options:0 range:NSMakeRange(range.location + 1, [sourceString length] - range.location - 1)];
}

Or just

[sourceString stringByReplacingOccurrencesOfString:searchString withString:targetString];

if you want to change the searchString to the same value everywhere in the source string.

like image 135
TheEye Avatar answered Nov 16 '22 21:11

TheEye


I would go with something like this:

// Setup what you're searching and what you want to find
NSString *string = @"abcabcabcabc";
NSString *toFind = @"abc";

// Initialise the searching range to the whole string
NSRange searchRange = NSMakeRange(0, [string length]);
do {
    // Search for next occurrence
    NSRange range = [string rangeOfString:toFind options:0 range:searchRange];
    if (range.location != NSNotFound) {
        // If found, range contains the range of the current iteration

        // NOW DO SOMETHING WITH THE STRING / RANGE

        // Reset search range for next attempt to start after the current found range
        searchRange.location = range.location + range.length;
        searchRange.length = [string length] - searchRange.location;
    } else {
        // If we didn't find it, we have no more occurrences
        break;
    }
} while (1);
like image 7
mattjgalloway Avatar answered Nov 16 '22 22:11

mattjgalloway


If you want to do changes, you could use:

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

but if that doesn't fit your needs try this:

- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block

like image 5
calimarkus Avatar answered Nov 16 '22 23:11

calimarkus