SimplyKiwi
SimplyKiwi

Reputation: 12444

Check for substring in string with NSString from NSArray?

So pretty much I want to check if my NSString from my NSArray is a substring of my string named imageName.

So lets say this:

  1. My Image name is: picture5of-batman.png
  2. My Array contains strings and one of them is: Batman

So pretty much I want to eliminate the: picture5of- part of the image name and replace it with the NSString from the NSArray.

This is how I try to do it but it never makes it to the if statement. And no my Array is not nil either. Here is the code:

for (NSString *string in superheroArray) {
    if ([string rangeOfString:imageName].location != NSNotFound) {
        //Ok so some string in superheroArray is equal to the file name of the image
        imageName = [imageName stringByReplacingOccurrencesOfString:@"" withString:string 
                                                      options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];

    }
}

Edit1: This still does not work

for (NSString *string in superheroArray) {
        if ([imageName rangeOfString:string options:NSCaseInsensitiveSearch].location != NSNotFound) {
            //Ok so some string in superheroArray is equal to the file name of the image
            imageName = string;
            //HOW ABOUT THAT FOR EFFICIENCY :P
        }

}

Upvotes: 3

Views: 1390

Answers (2)

勿绮语
勿绮语

Reputation: 9320

[imageName rangeOfString:string options: NSCaseInsensitiveSearch]

Upvotes: 5

Vincent Bernier
Vincent Bernier

Reputation: 8664

I don't see why it's not working in your code, maybe split the NSString stuff from the NSRage test.
but this work here :

     NSArray *ar = [NSArray arrayWithObjects:@"Batman", @"Maurice", nil];
__block NSString *imageName = @"picture5of-batman.png";
__block NSUInteger theIndex = -1;
[ar enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSRange r = [imageName rangeOfString: obj
                     options: NSCaseInsensitiveSearch];
    if (r.location != NSNotFound) 
    {
        theIndex = idx;
        NSString *str = [imageName pathExtension];
        imageName = [(NSString *)obj stringByAppendingPathExtension:str];
        //  you found it, so you can stop now
        *stop = YES;
    }
}];

if (theIndex != -1)
{
    NSLog(@"The index is : %d and new imageName == %@", theIndex, imageName);
}

And here is the NSLog statement :

2011-12-10 23:04:28.967 testSwitch1[2493:207] The index is : 0 and new imageName == Batman.png

Upvotes: 2

Related Questions