NSString range of string at occurrence <p>i'm trying to build a function that will tell me the range of a string at an occurrence.</p> <p>For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.</p> <p>I've tried building this simple function, but it doesn't work.</p> <p>Note - the top functions were constructed at an earlier date and work fine.</p> <p>Any help appreciated.</p> <pre><code>- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex { if (toCharacterIndex &gt; [stringToTrim length]) return @""; NSString *devString = [[[NSString alloc] init] autorelease]; for (int i = 0; i &lt;= toCharacterIndex; i++) { devString = [NSString stringWithFormat:@"%@%@", devString, [NSString stringWithFormat:@"%c", [stringToTrim characterAtIndex:(i-1)]]]; } return devString; [devString release]; } - (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex { if (fromCharacterIndex &gt; [stringToTrim length]) return @""; NSString *devString = [[[NSString alloc] init] autorelease]; for (int i = (fromCharacterIndex+1); i &lt;= [stringToTrim length]; i++) { devString = [NSString stringWithFormat:@"%@%@", devString, [NSString stringWithFormat:@"%c", [stringToTrim characterAtIndex:(i-1)]]]; } return devString; [devString release]; } - (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence { NSString *trimmedString = [inString copy]; //We start with the whole string. NSUInteger len, loc, oldLength; len = 0; loc = 0; NSRange tempRange = [string rangeOfString:substring]; len = tempRange.length; loc = tempRange.location; for (int i = 0; i != occurence; i++) { NSUInteger endOfWord = len+loc; trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord]; oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length]; NSRange tmp = [trimmedString rangeOfString:substring]; len = tmp.length; loc = tmp.location + oldLength; } NSRange returnRange = NSMakeRange(loc, len); return returnRange; } </code></pre>