1

在 PHP(这是我最熟悉的)中,它是一个单行表达式:

strpos('abc', 'b') !== false

Objective C 的等价物是什么?

4

3 回答 3

7
[@"abc" rangeOfString:@"b"].location != NSNotFound
于 2012-07-13T18:42:49.450 回答
3

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.

于 2012-07-13T18:48:52.680 回答
0
- (NSRange)rangeOfString:(NSString *)aString

返回值 一个 NSRange 结构,给出第一次出现的 aString 在接收器中的位置和长度。如果 aString 未找到或为空 (@""),则返回 {NSNotFound, 0}。

您可以在NSString 类参考中找到更多有用的字符串操作函数

于 2012-07-13T18:43:21.510 回答