在 PHP(这是我最熟悉的)中,它是一个单行表达式:
strpos('abc', 'b') !== false
Objective C 的等价物是什么?
[@"abc" rangeOfString:@"b"].location != NSNotFound
I think categories can be use to package up pieces of functionality like this very nicely.
@interface NSString (ContainsString)
- (BOOL)containsString:(NSString *)string;
@end
@implementation NSString (ContainsString)
- (BOOL)containsString:(NSString *)string
{
NSRange range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
return range.location != NSNotFound;
}
@end
When used, it makes the meaning very clear.
if ([@"this is a string" containsString:@"a string"]) {
…
}
In most projects this would be a part of a larger string method category and not it's own one-method category.
- (NSRange)rangeOfString:(NSString *)aString
返回值 一个 NSRange 结构,给出第一次出现的 aString 在接收器中的位置和长度。如果 aString 未找到或为空 (@""),则返回 {NSNotFound, 0}。
您可以在NSString 类参考中找到更多有用的字符串操作函数