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!
To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+
Secondly, in Swift String is a struct, while in Objective-C, NSString is a class and inherit from NSObject . In concept, Swift String is more likely immutable. If we use a struct type and constant (remember the let keyword), we can keep out a lot of consideration of multi-thread programming and make us a better life.
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
.
Give this a try:
NSRange range = [someNSStringHere rangeOfString:@" " options:NSBackwardsSearch];
NSString *result = [someNSStringHere substringFromIndex:range.location+1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With