ios nsrange char from end

2020-04-20 21:41发布

问题:

Let's say I have:

this - is an - example - with some - dashes

NSRange will pick up the first instance of "-" with `rangeOfString:@"-" but what if I only want the last one?

I'm looking for something that works similar to lastIndexOf in JS. Thanks!

回答1:

One of the options you can pass to [NSString rangeOfString: options:] is NSBackwardsSearch (which would give you the last item in the string you're looking at).



回答2:

There's another variant of the rangeOfString method:

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange

This lets you specify a range to search within, so you could, in a loop find each range and then exclude it from the search range and try again until there were no more matches.

Depending on what you are trying to do, you might have more luck using this:

NSArray *components = [string componentsSeparatedByString:@" - "];

That will split your string into each part that was separated by a @" - " and return them in an array - you can then get the last one using [components lastObject];

And yet another option is to use NSScanner, which is designed for looping through a string, grabbing tokens as you go.



标签: ios nsrange