Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
630 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...