How to filter a string after a particular character in iOS?

Francis F picture Francis F · Aug 16, 2013 · Viewed 7.3k times · Source

I want to filter string after character '='. For eg if 8+9=17 My output should be 17. I can filter character before '=' using NSScanner, how to do its reverse??? I need a efficient way to do this without using componentsSeparatedByString or creating an array

Answer

rmaddy picture rmaddy · Aug 16, 2013

Everyone seems to like to use componentsSeparatedByString but it is quite inefficient when you just want one part of a string.

Try this:

NSString *str = @"8+9=17";
NSRange equalRange = [str rangeOfString:@"=" options:NSBackwardsSearch];
if (equalRange.location != NSNotFound) {
    NSString *result = [str substringFromIndex:equalRange.location + equalRange.length];
    NSLog(@"The result = %@", result);
} else {
    NSLog(@"There is no = in the string");
}

Update:

Note - for this specific example, the difference in efficiencies is negligible if it is only being done once.

But in general, using componentsSeparatedByString: is going to scan the entire string looking for every occurrence of the delimiter. It then creates an array with all of the substrings. This is great when you need most of those substrings.

When you only need one part of a larger string, this is very wasteful. There is no need to scan the entire string. There is no need to create an array. There is no need to get all of the other substrings.