获取NSString的最后一个字 [英] Getting the last word of an NSString

查看:530
本文介绍了获取NSString的最后一个字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想从NSString中得到最后一句话。
我以为使用这段代码:

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;

但我认为NSArray如果它很大(并且它很大)会花费一些时间来加载,并且它不会识别用逗号分隔的单词。

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.

感谢您的帮助!

推荐答案

如果你想要超强健壮:

__block NSString *lastWord = nil;

[someNSStringHere enumerateSubstringsInRange:NSMakeRange(0, [someNSStringHere length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
    lastWord = substring;
    *stop = YES;
}];

(这也适用于非罗马语言; iOS 4 + / OS X 10.6+。)

(This should also work with non-Roman languages; iOS 4+/OS X 10.6+.)

基本解释:

-enumerateSubstringsInRage:options:usingBlock:执行它在锡上所说的内容:它枚举子字符串,这些子字符串由您作为选项传入的内容定义。 NSStringEnumerationByWords 说我想要给我的话, NSStringEnumerationReverse 说从字符串末尾开始而不是开头。

-enumerateSubstringsInRage:options:usingBlock: does what it says on the tin: it enumerates substrings, which are defined by what you pass in as the options. NSStringEnumerationByWords says "I want words given to me", and NSStringEnumerationReverse says "start at the end of the string instead of the beginning".

由于我们从最后开始,在 substring 中给我们的第一个单词将会是字符串中的最后一个单词,所以我们将 lastWord 设置为,然后设置 BOOL 指向停止为YES,因此枚举立即停止。

Since we're starting from the end, the first word given to us in substring will be the last word in the string, so we set lastWord to that, and then set the BOOL pointed to by stop to YES, so the enumeration stops right away.

lastWord 当然被定义为 __ block 所以我们可以在块中设置它并在外面看到它,它被初始化为 nil 所以如果字符串没有没有单词(例如,如果它是空的或者都是标点符号),当我们尝试使用 lastWord 。

lastWord is of course defined as __block so we can set it inside the block and see it outside, and it's initialized to nil so if the string has no words (e.g., if it's empty or is all punctuation) we don't crash when we try to use lastWord.

这篇关于获取NSString的最后一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆