如何检查string(NSString)是否包含另一个较小的字符串?
我希望有类似的东西:
NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
Run Code Online (Sandbox Code Playgroud)
但我能找到的最接近的是:
if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
Run Code Online (Sandbox Code Playgroud)
无论如何,这是查找字符串是否包含另一个字符串的最佳方法吗?
我想查看一个字符串,它是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 …Run Code Online (Sandbox Code Playgroud)