检查数组的元素是否包含指定的字符串
Checking whether elements of an Array contains a specified String
我正在开发 iOS 应用程序。我有一个数组,
NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for(int k=0; k<qwer.count; k++) {
//
}
我正在尝试检查我的数组是否包含字符串“wassail”。谁能帮我找到这个?
NSString
有一个 rangeOfString
函数,可用于查找部分字符串匹配。这个函数returnsNSRange
。您可以使用 location
属性.
...
NSArray *qwer = [NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for (NSString *name in qwer){
if ([name rangeOfString:keyword].location == NSNotFound) {
NSLog(@"contains");
}
}
...
参考:
- https://developer.apple.com/reference/foundation/nsstring/1416849-rangeofstring
- https://developer.apple.com/reference/foundation/nsrange
谢谢
斯里拉姆
试试这个
NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail",nil];
for(int k=0; k<qwer.count; k++) {
NSString *currentString =[qwer objectAtIndex:k];
if ([currentString rangeOfString:@"wassail"].location == NSNotFound) {
NSLog(@"string does not contain wassail");
} else {
NSLog(@"string contains wassail!");
break;
}
}
我正在开发 iOS 应用程序。我有一个数组,
NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for(int k=0; k<qwer.count; k++) {
//
}
我正在尝试检查我的数组是否包含字符串“wassail”。谁能帮我找到这个?
NSString
有一个 rangeOfString
函数,可用于查找部分字符串匹配。这个函数returnsNSRange
。您可以使用 location
属性.
...
NSArray *qwer = [NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for (NSString *name in qwer){
if ([name rangeOfString:keyword].location == NSNotFound) {
NSLog(@"contains");
}
}
...
参考:
- https://developer.apple.com/reference/foundation/nsstring/1416849-rangeofstring
- https://developer.apple.com/reference/foundation/nsrange
谢谢 斯里拉姆
试试这个
NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail",nil];
for(int k=0; k<qwer.count; k++) {
NSString *currentString =[qwer objectAtIndex:k];
if ([currentString rangeOfString:@"wassail"].location == NSNotFound) {
NSLog(@"string does not contain wassail");
} else {
NSLog(@"string contains wassail!");
break;
}
}