How do I use NSRange with this NSString?

Ethan Allen picture Ethan Allen · Mar 15, 2012 · Viewed 9.2k times · Source

I have the following NSString:

productID = @"com.sortitapps.themes.pink.book";

At the end, "book" can be anything.... "music", "movies", "games", etc.

I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:

partialID = @"com.sortitapps.themes.pink.";

Answer

sidyll picture sidyll · Mar 15, 2012

You can try a backward search for the dot and use the result to get the desired range:

NSString *str = @"com.sortitapps.themes.pink.book";
NSUInteger dot = [str rangeOfString:@"." options:NSBackwardsSearch].location;

NSString *newStr =
   [str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
                                withString:@"something_else"];