eon
eon

Reputation: 273

Finding Ranges Inside NSString Separated by a String

Although iOS provides a lot of useful string methods, I can't find a good solution for getting ranges of strings that are separated by a given character.

original string:

|You| will |achieve| everything you |want| if you |work| hard

separateness character is |.

separate string1: You (range: 3, 3)

separate string2: achieve (range: 12, 7)

separate string3: want (range: 37, 4)

separate string4: work (range: 51, 4)

NSString method's substringFromIndex: makes it possible to find these ranges using NSString, but this seems inefficient.

Please, let me know the better ways to solve this.

Upvotes: 2

Views: 2775

Answers (1)

Sam
Sam

Reputation: 27354

You should use NSRegularExpression's matchesInString:options:range: method.

Return Value

An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

You might have code like:

NSString *str = @"|You| will |achieve| everything you |want| if you |work| hard";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
    @"[^|]*" options: 0 error:nil];
NSArray *results = [regex matchesInString:str 
                                  options:0 
                                    range:NSMakeRange(0, [str length])];
// ... do interesting code on results...
// Note that you should iterate through the array and use the 'range' property
// to get the range.

for (NSTextCheckingResult *textResult in results)
{
   if (textResult.range.length > 0)
   {
      NSString *substring = [myStr substringWithRange:textResult.range];
      NSLog(@"string at range %@ :: \"%@\"", 
            NSStringFromRange(textResult.range), 
            substring);
   }
}

Logs:

string at range {1, 3} :: "You"

string at range {5, 6} :: " will "

string at range {12, 7} :: "achieve"

string at range {20, 16} :: " everything you "

string at range {37, 4} :: "want"

string at range {42, 8} :: " if you "

string at range {51, 4} :: "work"

string at range {56, 5} :: " hard"

Upvotes: 3

Related Questions