Getting the last word of an NSString - objective-c

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!

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 wanted to use a regular expression (which can be useful if you want to start getting more complicated in terms of what you're looking for at the end of your string), you could do something like:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\S+\\Z" options:0 error:nil];
NSTextCheckingResult *found = [regex firstMatchInString:inputString options:0 range:NSMakeRange(0, [inputString length])];
if (found.range.location != NSNotFound)
result = [inputString substringWithRange:found.range];

That works great as it also recognizes symbols like # and # which enumerateSubstringsInRange: doesn't do.
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *components = [someString componentsSeparatedByCharactersInSet:charSet];
NSString *lastWord = components.lastObject;

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: or substringWithRange:.

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

You could use NSString's function rangeOfSubstring: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, then r will be {NSNotFound, 0}
Hope I could help!
Ben

Related

Objective c comparing strings multiple words

Hi I'm looking to compare 2 strings using objective c. One string is a single word and the other will be one or more words. How can I cheeck for a match at word level? I.e if any word from the multiple word string matches my single word string return a 1 else return a 0 ? Any help much appreciated.
You might be tempted to use -[NSString rangeOfString:]:
if ([multipleWords rangeOfString:singleWord].location != NSNotFound)
return YES;
return NO;
But it's imperfect. You could have "returning" in multipleWords and singleWord could be "return", giving you a false positive.
So instead we must use NSRegularExpression.
NSString *single = #"returning";
NSString *multiple = #"a man is returning home";
NSString *pattern = [NSString stringWithFormat:#"\\b%#\\b",single];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange range = NSMakeRange(0, multiple.length);
NSUInteger matched = [regex numberOfMatchesInString:multiple options:0 range:range];
NSLog(#"number of matched = %ld", matched);
You can use NSString's rangeOfString method:
NSRange range = [multiWordString rangeOfString:oneWordString];
if (range.location == NSNotFound)
return 0;
else
return 1;
The above code will return 1 if you are searching for "WAR" inside the longer "I AM AWARE". Maybe you're looking for entire word match.
In that case you should split the long string into an array of single words using...
NSArray *singleWords = [multiWordString componentsSeparatedByString: #" "];
Then parse the array to find the oneWordString
You can split up words in a string into an array using [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]. You can then check each word in the array to see if it matches the single word being searched. It's not the most efficient way, but it could work for your needs.

String search in objective-c

Given a string like this:
http://files.domain.com/8aa55fc4-3015-400e-80f5-390997b43cf9/c07cb0d2-b7d7-4bfd-b0c3-6f43571e3c29-MyFile.jpg
I need to just locate the string "MyFile", and also tell what kind of image it is (.jpg or .png). How can I accomplish this?
The only thing I can think of is to search backward for the first four characters to get the file extension, then keep searching backward until I find the first hyphen, and assume the file name itself doesn't have any hyphens. But I don't know how to do that. Is there a better way?
Use NSRegularExpression to search for the file name. The search pattern really depends on what you know about the file name. If the "random" numbers and characters before MyFile has a known format, you could take that into account. My proposal below assumes that the file name doesn't contain any minus signs.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"-([:alnum:]*)\\.(jpg|png)$"
options:NSRegularExpressionSearch
error:nil];
// Get the match between the first brackets.
NSTextCheckingResult *match = [regex firstMatchInString:string options:0
range:NSMakeRange(0, [string length])];
NSRange matchRange = [match rangeAtIndex:1];
NSString *fileName = [string substringWithRange:matchRange];
NSLog(#"Filename: %#", fileName);
// Get the extension with a simple NSString method.
NSString *extension = [string pathExtension];
NSLog(#"Extension: %#", extension);
[myString lastPathComponent] will get the filename.
[myString pathExtension] will get the extension.
To get the suffix of the filename, I think you'll have to roll your own parse. Is it always the string after the last dash and before the extension?
If so, here's an idea:
- (NSString *)lastLittleBitOfTheFilenameFrom:(NSString *)filename {
NSInteger fnStart = [filename rangeOfString:#"-" options:NSBackwardsSearch].location + 1;
NSInteger fnEnd = [filename rangeOfString:#"." options:NSBackwardsSearch].location;
// might need some error checks here depending on what you expect in the original url
NSInteger length = fnEnd - fnStart;
return [filename substringWithRange:NSMakeRange(fnStart, length)];
}
Or, thanks to #Chuck ...
// even more sensitive to unexpected input, but nice and tiny ...
- (NSString *)lastLittleBitOfTheFilenameFrom:(NSString *)filename {
NSString *nameExt = [[filename componentsSeparatedByString:#"-"] lastObject];
return [[nameExt componentsSeparatedByString:#"."] objectAtIndex:0];
}
If you have the string in an NSString object, or create it from that string, you may use the rangeOfString method to acomplish both.
See https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html for more details.

Objective-C NSString character substitution

I have a NSString category I am working on to perform character substitution similar to PHP's strtr. This method takes a string and replaces every occurrence of each character in fromString and replaces it with the character in toString with the same index. I have a working method but it is not very performant and would like to make it quicker and able to handle megabytes of data.
Edit (for clarity):
stringByReplacingOccurrencesOfString:withString:options:range: will not work. I have to take a string like "ABC" and after replacing "A" with "B" and "B" with "A" end up with "BAC". Successive invocations of stringByReplacingOccurrencesOfString:withString:options:range: would make a string like "AAC" which would be incorrect.
Suggestions would be great, sample code would be even better!
Code:
- (NSString *)stringBySubstitutingCharactersFromString:(NSString *)fromString
toString:(NSString *)toString;
{
NSMutableString *substitutedString = [self mutableCopy];
NSString *aCharacterString;
NSUInteger characterIndex
, stringLength = substitutedString.length;
for (NSUInteger i = 0; i < stringLength; ++i) {
aCharacterString = [NSString stringWithFormat: #"%C", [substitutedString characterAtIndex:i]];
characterIndex = [fromString rangeOfString:aCharacterString].location;
if (characterIndex == NSNotFound) continue;
[substitutedString replaceCharactersInRange:NSMakeRange(i, 1)
withString:[NSString stringWithFormat:#"%C", [toString characterAtIndex:characterIndex]]];
}
return substitutedString;
}
Also this code is executed after every change to text in a text view. It is passed the entire string every time. I know that there is a better way to do it, but I do not know how. Any suggestions for this would be most certainly appreciated!
You can make that kind of string substitution with NSRegularExpression either modifying an mutable string or creating a new immutable string. It will work with any two strings to substitute (even if they are more than one symbol) but you will need to escape any character that means something in a regular expression (like \ [ ( . * ? + etc).
The pattern finds either of the two substrings with the optional "anything" between and than replaces them with the two substrings with each other preserving the optional string between them.
// These string can be of any length
NSString *firstString = #"Axa";
NSString *secondString = #"By";
// Escaping of characters used in regular expressions has NOT been done here
NSString *pattern = [NSString stringWithFormat:#"(%#|%#)(.*?)(%#|%#)", firstString, secondString, firstString, secondString];
NSString *string = #"AxaByCAxaCBy";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
// Insert error handling here...
}
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"$3$2$1"];
NSLog(#"Before:\t%#", string); // AxaByCAxaCBy
NSLog(#"After: \t%#", modifiedString); // ByAxaCByCAxa

Getting index of a character in NSString with offset & using substring in Objective-C

I have a string!
NSString *myString=[NSString stringWithFormat:#"This is my lovely string"];
What I want to do is:
Assuming the first character in the string is at index 0. Go to the 11th character (That is 'l' in the above case), and find the position of first occurring space backwards (In the above string, the position of first occurring space if we go backwards from 'l' is at position 10). Let's call the index of this space 'leSpace' having value 10.
Substring the remaining string to a new string using ...
[myString substringFromIndex:leSpace]
...I hope I have explained well. Please help, can you write a snippet or something to help me do this task?
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
For the options use: NSBackwardsSearch
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
Example:
NSString *myString=[NSString stringWithFormat:#"This is my lovely string"];
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
NSLog(#"range.location: %lu", range.location);
NSString *substring = [myString substringFromIndex:range.location+1];
NSLog(#"substring: '%#'", substring);
NSLog output:
range.location: 10
substring: 'lovely string'
Of course there should be error checking that range.location does not equal NSNotFound

Objective-C, rangeOfString from an offset

is it possible to use the method rangeOfString to search for a NSString starting from a given offset?
Something more similar to the strpos function in PHP.
Thanks
Not -rangeOfString:, but a similar method - -rangeOfString:options:range:.
(Edit: An example)
NSString *string = #"YaddaYaddaYadda";
NSString *searchString = #"Yadda";
NSRange thisCharRange, searchCharRange;
searchCharRange = NSMakeRange(3, [string length]);
thisCharRange = [string rangeOfString:searchString options:0 range:searchCharRange];
NSLog(#"thisCharRange: %#", NSStringFromRange(thisCharRange));
I find a problem with the example up there. It'll cause "Range or index out of bounds".
searchCharRange = NSMakeRange(3, [string length]);
should change to
searchCharRange = NSMakeRange(3, [string length] - 3);
that is,the range's length should not be longer than the original string's length - the range's start location.