开发者

How to compare two NSString efficiently

开发者 https://www.devze.com 2023-04-10 17:30 出处:网络
I know it is possible to use the methods compare: and isEqua开发者_如何学PythonlToString:, and I suppose isEqualToString is the most efficient method If you know it´s an string. But my question is, i

I know it is possible to use the methods compare: and isEqua开发者_如何学PythonlToString:, and I suppose isEqualToString is the most efficient method If you know it´s an string. But my question is, is there another way to do it more efficiently? Like comparing char by char or something like that.


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. When this method compares two strings, if the individual Unicodes are the same, then the strings are equal, regardless of the backing store. “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character.

and:

When you know both objects are strings, this method is a faster way to check equality than 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. Simple and efficient!


isEqualToString: is faster if you know both objects are strings, as the documentation states.


You could try converting both string to C strings and then use strcmp. Doubt it'll actually be any quicker though.

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

精彩评论

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

关注公众号