2

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.";
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

3 Answers3

7

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"];
sidyll
  • 57,726
  • 14
  • 108
  • 151
2

Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:

[productID stringByDeletingPathExtension];

Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
tarmes
  • 15,366
  • 10
  • 53
  • 87
2

You can use -[NSString componentsSeparatedByString:@"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:@"."] to join your modified array into a string again.

Kekoa
  • 27,892
  • 14
  • 72
  • 91
  • Although NSRange is the correct solution to this, I ended up using your solution instead because it's easier to understand and manipulate. The reason this really shouldn't be used is because Apple/iOS doesn't guarantee the order of the array will be correct (although it always is in practice). – Ethan Allen Mar 15 '12 at 19:55
  • Actually, from [NSString Class Reference](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html): _The substrings in the array appear in the order they did in the receiver._ – EmilioPelaez Mar 15 '12 at 20:03
  • Yes, my answer is to the question that begat this question :) – Kekoa Mar 15 '12 at 20:11