If you want to be super-reliable:
__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 +.)
The main explanation:
-enumerateSubstringsInRage:options:usingBlock:
does what it says about the gesture: it lists the substrings that are determined by what you pass as parameters. NSStringEnumerationByWords
says: “I need the words given to me,” and NSStringEnumerationReverse
says “start at the end of the line, not at the beginning”.
Since we start from the end, the first word given to us in substring
will be the last word in the string, so we set lastWord
for it, and then set the BOOL
pointed to by stop
in YES, so the listing stops right away.
lastWord
, of course, is defined as __block
, so we can set it inside the block and see it outside and initialize to nil
, so if the line has no words (for example, if it is empty or all punctuation is used), we will not fail when we try to use lastWord
.
Wevah source share