Finding a substring in a NSString object Finding a substring in a NSString object objective-c objective-c

Finding a substring in a NSString object


NSRange range = [string rangeOfString:@"ate"];NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];


NSString *str = @"The dog ate the cat";NSString *search = @"ate";NSString *sub = [str substringFromIndex:NSMaxRange([str rangeOfString:search])];

If you want to trim whitespace you can do that separately.


What about this way?It's nearly the same. But maybe meaning of NSRange easier to understand for beginners, if it's written this way.

At last, it's the same solution of jtbandes

    NSString *szHaystack= @"The dog ate the cat";    NSString *szNeedle= @"ate";    NSRange range = [szHaystack rangeOfString:szNeedle];    NSInteger idx = range.location + range.length;    NSString *szResult = [szHaystack substringFromIndex:idx];