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!
You could use
NSString
's functionrangeOfSubstring:options:
to determine it. For example:Search the string for a space, using a backwards search option to start the search from the end of the string.
NSRange r = [string rangeOfString:@" " options:NSBackwardsSearch];
This will find the location of the last word of the string. Now just get the string using
substringWithRange:
For Example:NSRange found = NSMakeRange(NSMaxRange(r), string.length - NSMaxRange(r)); NSString *foundString = [string substringWithRange:found];
Where
r
is the range from earlier.Also be careful to make sure that you check
r
actually exists. If there is only 1 word in the string, thenr
will be{NSNotFound, 0}
Hope I could help!
Ben
If you want to be super-robust:
(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", andNSStringEnumerationReverse
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 setlastWord
to that, and then set theBOOL
pointed to bystop
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 tonil
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 uselastWord
.You can read symbols from the end of the your string and copy them at the 0 index to result string. Whether you read space or comma, result string wil contain the last word
That works great as it also recognizes symbols like @ and # which
enumerateSubstringsInRange:
doesn't do.The most efficient way is likely to start at the end of the string, examine each character to see if it's part of what you define as a word, and then extract the word you want using
substringFromIndex:
orsubstringWithRange:
.Give this a try: