如何查看字符串是否包含子字符串(objective-c)

use*_*985 2 string xcode compare substring objective-c

我想查看一个字符串,它是apple rss新闻源上帖子的标题是否包含子字符串,例如"Steve"或"Jobs".我把帖子组织成了一个uitableview.

所以有一个帖子里有史蒂夫或乔布斯的标题所以我用它来检查:

   if ([[entry title] localizedCaseInsensitiveCompare:@"Steve"] == NSOrderedSame ||        [[entry title] localizedCaseInsensitiveCompare: @"Jobs"] == NSOrderedSame) {

    NSLog(@"Comparism of Steve Jobs");
    cell.imageView.image = [UIImage imageNamed:@"steve.png"];
}
Run Code Online (Sandbox Code Playgroud)

但它从未调用过,entry是一个包含标题的RSSItem类 - 条目及其标题不是我的问题,我已经检查过.我的比较是问题所在.我如何比较

UPDATE!

好的,这里是代码:

NSRange range = [[[cell textLabel] text] rangeOfString:@"Steve" options:NSCaseInsensitiveSearch];

if (range.location != NSNotFound) 
{
    cell.imageView.image = [UIImage imageNamed:@"steve.png"];


}
Run Code Online (Sandbox Code Playgroud)

我已尝试过其他人的方式,但同样的结果:

有些单元格的imageView为steve.png,即使它们的标题不包含史蒂夫作业.奇怪的???我向下滚动,当我回到原位时,所有重新分配和初始化的出列单元都有史蒂夫作业图片.在我打开应用程序的时候,一些在标题中没有史蒂夫的细胞都有了图像,然后发生了上述情况.

我需要的周围代码如下:

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:@"UITableViewCell"]
            autorelease];
}


tableView.autoresizingMask = 5;
tableView.autoresizesSubviews = YES;
cell.autoresizingMask = 5;
cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 20, 20);
RSSItem *item = [[channel items] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[item title]];
NSMutableString *string = [[NSMutableString alloc] initWithString:[[cell textLabel] text]];

if (string.length > 46) {
    cell.textLabel.numberOfLines = 2;
    UILineBreakMode lineBreak = UILineBreakModeClip;
    cell.textLabel.lineBreakMode = lineBreak;

}

[string release];

tableView.backgroundColor = [UIColor darkGrayColor];
cell.textLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size: 12.0];
cell.backgroundColor = [UIColor whiteColor];

NSRange range = [[[cell textLabel] text] rangeOfString:@"Steve" options:NSCaseInsensitiveSearch];

if (range.location != NSNotFound) 
{
    cell.imageView.image = [UIImage imageNamed:@"steve.png"];


    }



return cell;

    }
Run Code Online (Sandbox Code Playgroud)

Jos*_*sen 12

NSString-rangeOfString返回一个NSRange,可以检查"未找到"的情况.

if ([@"Some awesome string." rangeOfString:@"awesome"].location != NSNotFound)
{
  // awesome is in 'Some awesome string.'
}
else 
{
 // awesome is not in 'Some awesome string.' 
}
Run Code Online (Sandbox Code Playgroud)


Hot*_*cks 6

你正在比较整个字符串,"史蒂夫乔布斯"不会匹配"史蒂夫"或"乔布斯".你可能想要使用rangeOfString:@"Steve" options:NSCaseInsensitiveSearch,或者其他一些.