If you want to be super-robust:
__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;
}];
(This should also work with non-Roman languages; iOS 4+/OS X 10.6+.)
Basic explanation:
-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".
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
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…