ios 如何检查 NSString = 特定的字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7266218/
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 to check if NSString = a specific string value?
提问by C.Johns
Hi I am woundering if you can check to see if a NSString equals a specific value say for instance a name of a person?
嗨,如果你能检查一个 NSString 是否等于一个特定的值,比如一个人的名字,我很伤心?
I am thinking along the lines of
我在思考
if (mystring == @"Johns"){
//do some stuff in here
}
回答by Vanya
if ([mystring isEqualToString:@"Johns"]){
//do some stuff in here
}
回答by Robert
Here is another method you might want to use in some circumstances:
这是您在某些情况下可能想要使用的另一种方法:
NSArray * validNames = @[ @"foo" , @"bar" , @"bob" ];
if ([validNames indexOfObject:myString].location != NSNotFound)
{
// The myString is one of the names in the valid names array
}
Or if you have a large amount of names in the array you could use a NSSet
, since finding an object is faster than in an array ((O(Log N)
vs O(N)
)
或者,如果数组中有大量名称,则可以使用 a NSSet
,因为查找对象比在数组中更快((O(Log N)
vs O(N)
)
NSSet * validNamesSet = [NSSet setWithArray:validNames];
if ([validNamesSet containsObject:myString])
{
// This is faster than indexOfObject for large sets
}
These methods work because NSSet
and NSArray
use isEqual:
which will call isEqualToString:
for NSString
instances.
这些方法的工作,因为NSSet
和NSArray
使用isEqual:
,它将调用isEqualToString:
的NSString
实例。