有没有更好的方法来比较一个字符串与多个字符串?
我想将一个字符串与多个字符串进行比较。例如,
if([var isEqualToString:@"Box"]||[var isEqualToString:@"Ball"]|[varisEqualToString:@"Bat"])
{
some function
}else{
some function
}
在我的例子中,我必须与 15 个字符串进行比较,所以我必须检查 15 次。是否有其他更好的方法来比较它。是否有任何简单的小代码可以实现我的逻辑。
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 small simple code will implement my logic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您最好将字符串添加到 NSSet 中,如下所示:
许多其他解决方案使用数组或字典来实现相同目的。集合是正确的数据结构,因为它们是为了包含无序对象和测试成员资格而创建的。我非常确定
containsObject:
与需要进行元素搜索的NSArray
中的相同方法相比,运行时间恒定。You're better off adding the strings to an NSSet as follows:
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 inNSArray
which needs to do an element search.将字符串放入 NSDictionary 中:
字典查找的时间复杂度为 O(1),而数组搜索的时间复杂度可能为 O(log n)。对于 15 个元素来说没什么大不了的,但作为一般规则,字典或集合可能会表现得更好。如果您经常进行这种搜索/比较,需要考虑一些事情。
编辑
正如我所提到的,
NSSet
也会在 O(1) 时间内进行查找:绝对是更干净的代码,但我认为
NSSet
实例需要创造时间要长得多。但这样你就只需要做一次,对吗?Put your strings into an
NSDictionary
: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: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
Not really better, but possibly more readable.