xcode 我如何检查特定的 NSString 是否存在于 NSArray 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7396919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How might I check if a particular NSString is present in an NSArray?
提问by Ravi
How might I check if a particular NSString is presnet in an NSArray?
我如何检查特定的 NSString 是否是 NSArray 中的 presnet?
回答by Janak Nirmal
You can do it like,
你可以这样做,
NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
// do found
} else {
// do not found
}
回答by bryanmac
Iterating or containsObject are order n ways to find.
迭代或 containsObject 是 n 阶查找方法。
If you want constant time lookup, you can also maintain a hash table like NSSet or NSHashTable but that increases space but saves time.
如果您想要恒定时间查找,您还可以维护一个哈希表,如 NSSet 或 NSHashTable,但这会增加空间但节省时间。
NSArray* strings = [NSArray arrayWithObjects: @"one", @"two", @"three", nil];
NSSet *set = [NSSet setWithArray:strings];
NSString* stringToFind = @"two";
NSLog(@"array contains: %d", (int)[strings containsObject:stringToFind]);
NSLog(@"set contains: %d", (int)[set containsObject:stringToFind]);
回答by Steven Fisher
Depends on your needs. Either indexOfObject
if you care about equality (most likely), or indexOfObjectIdenticalTo
if you care it's actually the same object (i.e. same address).
取决于您的需求。无论是indexOfObject
如果你关心平等(最有可能),或者indexOfObjectIdenticalTo
如果你关心它实际上是相同的对象(即同一个地址)。
Source:
来源: