开发者

Is there any better way for comparing a string with multiple strings?

I want to compare a string with multiple string.For ex

if([var isEqualToString:@"Box"]||[var isEqualToString:@"Ball"]|[varisEqualToString:@"Bat"])
{
some function
}else{
some function
}

In my case I have to compare with 15 string, so I have to check for 15 times.Is there any other better way to compare it. Is there any开发者_如何学Python small simple code will implement my logic.


You're better off adding the strings to an NSSet as follows:

NSSet *mySet = [NSSet setWithObjects:@"Box", @"Ball", @"Bat", nil];
if([mySet containsObject:string]) {
} else {
}

A lot of the other solutions use arrays or dictionaries for the same purpose. Sets are the correct data structure for this since they are created for the purpose of containing unordered objects and testing membership. I'm pretty sure containsObject: runs in constant time compared to the same method in NSArray which needs to do an element search.


Put your strings into an NSDictionary:

NSNull *nullValue = [NSNull null];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:nullValue, nullValue, ..., nil forKeys:@"Box", @"Ball", ..., nil];
if ([dictionary objectForKey:var]) {
    // var matches one of the keys, run function 
}
else { 
    // var doesn't match any of the keys, do something else
}

Dictionary lookups are O(1), whereas an array search is probably O(log n). Not a big deal for 15 elements, but as a general rule a dictionary or set will likely perform better. Something to think about if you do this search/comparison a lot.

EDIT

As I mentioned, an NSSet will also do lookups in O(1) time:

NSSet *comparisonSet = [NSSet setWithObjects:@"Box", @"Ball", ..., nil];
if ([comparisonSet containsObject:var]) {
    // var matches set object, run function
} 
else {
    // var doesn't match any of the set objects, do something else
}

Cleaner code, definitely, but I think NSSet instances take much longer to create. But then you only have to do it once, right?


You could create an array using

NSArray *stringArray = [NSArray arrayWithObjects: @"Box", @"Ball", @"Bat", nil];
if([NSArray indexOfObject:var] != NSNotFound)
{
   ...
}
else
{
   ...
}

Not really better, but possibly more readable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜