Question

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

Was it helpful?

Solution

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.

OTHER TIPS

NSArray * array = [string componentsSeparatedByString:@"="];
if (array)
{
    NSString * desiredString = (NSString *)[array lastObject]; //or whichever the index
}
else
{
    NSLog(@""); //report error - = not found. Of array could somehow be not created.
}

NOTE: Though this is very popular splitting solution, it is only worth trying whenever every substring separated by separator string is required. rmaddy's answer suggest better mechanism whenever the need is only to get small part of the string. Use that instead of this approach whenever only small part of the string is required.

Try to use this one

        NSArray *arr = [string componentsSeparatedByString:@"="];
        if (arr.count > 0)
        {
            NSString * firstString = [arr objectAtIndex:0];
            NSString * secondString = [arr objectAtIndex:1];
            NSLog(@"First String %@",firstString);
            NSLog(@"Second String %@",secondString);
        }

Output

First String 8+9

Second String 17

Use this:

 NSString *a =@"4+6=10";
    NSLog(@"%@",[a componentsSeparatedByString:@"="])

;

 Log: Practice[7582:11303] (
        "4+6",
        10
    )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top