How might I check if a particular NSString is presnet in an NSArray?
我如何检查特定的NSString是否是NSArray中的presnet?
3 个解决方案
#1
45
You can do it like,
你可以这样做,
NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
// do found
} else {
// do not found
}
#2
6
Iterating or containsObject are order n ways to find.
Iterating或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]);
#3
1
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:
资源:
- NSArray Class Reference
- NSArray类参考
#1
45
You can do it like,
你可以这样做,
NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
// do found
} else {
// do not found
}
#2
6
Iterating or containsObject are order n ways to find.
Iterating或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]);
#3
1
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:
资源:
- NSArray Class Reference
- NSArray类参考