Getting the last word of an NSString

2020-02-10 06:48发布

As the title suggests, I would like to get the last word out of an NSString. I thought using this code:

NSArray *listItems = [someNSStringHere componentsSeparatedByString:@" "];
NSString *lastWordString = [NSString stringWithFormat:@"%@", listItems.lastObject];
anotherNSStringHere = lastWordString;

But I think the NSArray will take a time to load if it's big (and it is big), and it wouldn't recognize a word separated by a comma.

Thanks for helping!

7条回答
劫难
2楼-- · 2020-02-10 07:41

If you wanted to use a regular expression (which can be useful if you want to start getting more complicated in terms of what you're looking for at the end of your string), you could do something like:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\S+\\Z" options:0 error:nil];
NSTextCheckingResult *found = [regex firstMatchInString:inputString options:0 range:NSMakeRange(0, [inputString length])];

if (found.range.location != NSNotFound)
    result = [inputString substringWithRange:found.range];
查看更多
登录 后发表回答