简体   繁体   中英

ios nsrange char from end

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!

可以传递给[NSString rangeOfString: options:]是NSBackwardsSearch(它将为您提供正在查找的字符串中的最后一项)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM