Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use NSRange with this NSString?

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.";
like image 834
Ethan Allen Avatar asked Mar 14 '26 05:03

Ethan Allen


2 Answers

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"];
like image 149
sidyll Avatar answered Mar 16 '26 23:03

sidyll


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.

like image 24
Kekoa Avatar answered Mar 16 '26 21:03

Kekoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!