String comparison for localization

梦想的初衷 提交于 2019-12-05 00:09:45

问题


What is the difference between NSString's localizedCaseInsensitiveCompare: and localizedStandardCompare: methods?

I read the reference but did not get a proper idea of which one to use.


回答1:


localizedCaseInsensitiveCompare: is equivalent to:

[aString compare:otherString
         options:NSCaseInsensitiveSearch
         range:NSMakeRange(0,aString.length)
        locale:[NSLocale currentLocale]];

localizedStandardCompare: is basically equivalent to:

[aString compare:otherString
         options:NSCaseInsensitiveSearch | NSNumericSearch
         range:NSMakeRange(0,aString.length)
        locale:[NSLocale currentLocale]];

So, the primary difference is in how numbers within strings are compared.

Comparing the following 3 strings using localizedCaseInsensitiveCompare: would result in the following order:

"Foo2.txt",
"Foo25.txt",
"Foo7.txt"

On the other hand, comparing them using localizedStandardCompare: would result in the following order:

"Foo2.txt",
"Foo7.txt",
"Foo25.txt"

While the localizedCaseInsensitiveCompare: method has been around forever, the localizedStandardCompare: was only added recently (OS X 10.6). The Finder sorts filenames using the numeric method, and prior to the addition of localizedStandardCompare:, developers were without an easy way to assure they could sort strings like the Finder did.

When determining which one to use, if the strings you're comparing represent filenames, then you should definitely tend toward using localizedStandardCompare:.




回答2:


The latter sorts like Finder on OS X.




回答3:


localizedCaseInsensitiveCompare: is similar to localizedCompare:

They both return an NSComparisonResult value that indicates the lexical ordering of the receiver and another given string using a localized comparison.

The difference being that the former is case insensitive. i.e. it ignores the differing use of uppercase and lowercase letters when comparing the strings.

localizedStandardCompare This compares strings as sorted by the Finder Application.



来源:https://stackoverflow.com/questions/15436143/string-comparison-for-localization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!