Search code examples
iphonensstringnsrange

nsstring replace string in range


I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :

NSString *string = @"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;

// Determine "{" location
NSRange startRange = [string rangeOfString:@"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
    // Determine "}" location according to "{" location
    NSRange endRange;

    endRange.location = startRange.length + startRange.location;
    endRange.length   = [string length] - endRange.location;
    endRange = [string rangeOfString:@"}" options:NSCaseInsensitiveSearch range:endRange];

    if (endRange.location != NSNotFound)
    {
        // bracets found: retrieve string between them
        startRange.location += startRange.length;
        startRange.length = endRange.location - startRange.location;

        result = [string substringWithRange:startRange];

    }
}

Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.


Solution

  • Try this one:

    NSString *string = @"{Hello} ({World}) ({How}) ({Are}) ({You})";
        //NSString *result = nil;
    
        // Determine "{" location
    
        NSArray *array=[string componentsSeparatedByString:@"{"];
        for(NSString *str in array){
            NSString *newString=[[str componentsSeparatedByString:@"}"] objectAtIndex:0];
        NSLog(@"%@",newString);
        }