简体   繁体   English

如何有效地比较两个NSString

[英]How to compare two NSString efficiently

I know it is possible to use the methods compare: and isEqualToString: , and I suppose isEqualToString is the most efficient method If you know it´s an string. 我知道可以使用compare:isEqualToString: ,并且我想isEqualToString是最有效的方法(如果您知道它是一个字符串)。 But my question is, is there another way to do it more efficiently? 但是我的问题是,还有另一种方法可以更有效地做到这一点吗? Like comparing char by char or something like that. 就像逐个字符比较char之类的。

By reading the documentation: 通过阅读文档:

The comparison uses the canonical representation of strings, which for a particular string is the length of the string plus the Unicode characters that make up the string. 比较使用字符串的规范表示形式,对于特定的字符串,它是字符串的长度加上组成字符串的Unicode字符。 When this method compares two strings, if the individual Unicodes are the same, then the strings are equal, regardless of the backing store. 当此方法比较两个字符串时,如果各个Unicode相同,则无论后备存储如何,字符串都是相等的。 “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. 当将“文字”应用于字符串比较时,表示不应用各种Unicode分解规则,并且分别比较Unicode字符。 So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character. 因此,例如,表示为组合字符序列“ O”和变音符号的“Ö”将不等于表示为一个Unicode字符的“Ö”。

and: 和:

When you know both objects are strings, this method is a faster way to check equality than isEqual:. 当您知道两个对象都是字符串时,此方法是比isEqual:更快的检查相等性的方法。

it seems that it's the best method available, to compare strings and that it does exactly what you need, that is: first it checks for length (if 2 strings have different length, is not necessary to check each char contained), then if the length it's the same it compares each char. 似乎这是比较字符串的最佳方法,它确实满足您的需要,即:首先检查长度(如果2个字符串的长度不同,则不必检查所包含的每个字符),然后如果长度相同,比较每个字符。 Simple and efficient! 简单高效!

isEqualToString:如果您知道两个对象都是字符串,则速度更快,如文档所述。

You could try converting both string to C strings and then use strcmp. 您可以尝试将两个字符串都转换为C字符串,然后使用strcmp。 Doubt it'll actually be any quicker though. 怀疑它实际上会更快。

char *str1 = [myNSString1 UTF8String];
char *str2 = [myNSString2 UTF8String];
BOOL isEqual = strcmp(str1,str2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM