2011-12-11 105 views
3

所以我非常想检查我的NSArray中的NSString是否是我的名为imageName的字符串的子字符串。使用NSArray的NSString检查字符串中的子字符串?

因此,可以说本:

  1. 我的形象的名字是:picture5of-batman.png
  2. 我的数组包含字符串,其中之一是:蝙蝠侠

所以非常想消除:picture5of-图像名称的一部分,并将其替换为NSArray中的NSString。

这是我如何尝试这样做,但它从来没有使它的if语句。而且我的阵列也不是零。下面是代码:

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:这仍然不起作用

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 
     } 

}

回答

5
[imageName rangeOfString:string options: NSCaseInsensitiveSearch] 
+0

检查我的edit1。 –

+0

如何轻松摆脱像_和空格这样的东西,确保它能正常工作? –

2

我不明白为什么它不是在你的代码的工作,也许从NSRage测试中拆分NSString的东西。
但这项工作在这里:

 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); 
} 

这里是的NSLog声明:

2011-12-10 23:04:28.967 testSwitch1 [2493:207]该指数是:0和新imageName = = Batman.png

+0

好的,但我怎么会实际上修改imageName只包括找到匹配的字符串? –

+0

你想要的最终结果是什么?因为在你的问题中,你建议你想要结束Batmanbatman.png。那是你要的吗? –

+0

不只是Batman.png –

相关问题