07. Searching, Comparing, and Sorting Strings

The string classes provide methods for finding characters and substrings within strings and for comparing one string to another. These methods conform to the Unicode standard for determining whether two character sequences are equivalent. The string classes provide comparison methodsthat handle composed character sequences properly, though you do have the option of specifying a literal search when efficiency is important and you can guarantee some canonical form for composed character sequences.

  • 字符串类提供了在字符串中查找字符和子字符串以及将一个字符串与另一个字符串进行比较的方法。 这些方法符合Unicode标准,用于确定两个字符序列是否相同。 字符串类提供了正确处理组合字符序列的比较方法,尽管您可以选择在效率很重要时指定文字搜索,并且可以保证组合字符序列的某些规范形式。

Search and Comparison Methods

  • 搜索和比较方法

The search and comparison methods each come in several variants. The simplest version of each searches or compares entire strings. Other variants allow you to alter the way comparison of composed character sequences is performed and to specify a specific range of characters within a string to be searched or compared; you can also search and compare strings in the context of a given locale.

  • 搜索和比较方法分别有几种变体。 每个最简单的版本搜索或比较整个字符串。 其他变体允许您更改组合字符序列的比较方式,并指定要搜索或比较的字符串中的特定字符范围; 您还可以在给定语言环境的上下文中搜索和比较字符串。

These are the basic search and comparison methods:

  • 这些是基本的搜索和比较方法:
07. Searching, Comparing, and Sorting Strings_第1张图片
image.png

Searching strings

You use the rangeOfString:... methods to search for a substring within the receiver. The rangeOfCharacterFromSet:... methods search for individual characters from a supplied set of characters.

  • 您可以使用rangeOfString:...方法在接收器中搜索子字符串。 rangeOfCharacterFromSet:...方法从提供的字符集中搜索单个字符。

Substrings are found only if completely contained within the specified range. If you specify a range for a search or comparison method and don’t request NSLiteralSearch (see below), the range must not break composed character sequences on either end; if it does, you could get an incorrect result. (See the method description for rangeOfComposedCharacterSequenceAtIndex: for a code sample that adjusts a range to lie on character sequence boundaries.)

  • 仅在完全包含在指定范围内时才会找到子字符串。 如果为搜索或比较方法指定范围而不请求NSLiteralSearch(见下文),则范围不得破坏任何一端的组合字符序列; 如果是这样,你可能得到一个不正确的结果。 (请参阅rangeOfComposedCharacterSequenceAtIndex的方法说明:以获取将范围调整为位于字符序列边界上的代码示例。)

You can also scan a string object for numeric and string values using an instance of NSScanner. For more about scanners, see Scanners. Both the NSString and the NSScanner class clusters use the NSCharacterSet class cluster for search operations. For more about character sets, see Character Sets.

  • 您还可以使用NSScanner实例扫描字符串对象的数值和字符串值。 有关扫描仪的更多信息,请参阅扫描仪。 NSString和NSScanner类集群都使用NSCharacterSet类集群进行搜索操作。 有关字符集的更多信息,请参阅字符集。

If you simply want to determine whether a string contains a given pattern, you can use a predicate:

  • 如果您只想确定字符串是否包含给定模式,则可以使用谓词:

For more about predicates, see Predicate Programming Guide.

  • 有关谓词的更多信息,请参阅谓词编程指南。

Comparing and sorting strings

The compare:... methods return the lexical ordering of the receiver and the supplied string. Several other methods allow you to determine whether two strings are equal or whether one is the prefix or suffix of another, but they don’t have variants that allow you to specify search options or ranges.

  • compare:...方法返回接收者的词法排序和提供的字符串。 其他几种方法允许您确定两个字符串是否相等,或者一个是否是另一个字符串的前缀或后缀,但它们没有允许您指定搜索选项或范围的变体。

The simplest method you can use to compare strings is compare: —this is the same as invoking compare:options:range: with no options and the receiver’s full extent as the range. If you want to specify comparison options (NSCaseInsensitiveSearch, NSLiteralSearch, or NSNumericSearch) you can use compare:options:; if you want to specify a locale you can use compare:options:range:locale:. NSString also provides various convenience methods to allow you to perform common comparisons without the need to specify ranges and options directly, for example caseInsensitiveCompare: and localizedCompare:.

  • 比较字符串的最简单方法是比较: - 这与调用compare相同:options:range:没有选项,接收者的完整范围作为范围。 如果要指定比较选项(NSCaseInsensitiveSearch,NSLiteralSearch或NSNumericSearch),可以使用compare:options:; 如果要指定区域设置,可以使用compare:options:range:locale:。 NSString还提供了各种便捷方法,允许您执行常见的比较,而无需直接指定范围和选项,例如caseInsensitiveCompare:和localizedCompare:。

Important: For user-visible sorted lists, you should always use localized comparisons. Thus typically instead of compare: or caseInsensitiveCompare: you should use localizedCompare: or localizedCaseInsensitiveCompare:.

  • 重要说明:对于用户可见的排序列表,应始终使用本地化比较。 因此,通常不使用compare:或caseInsensitiveCompare:您应该使用localizedCompare:或localizedCaseInsensitiveCompare:。

If you want to compare strings to order them in the same way as they’re presented in Finder, you should use compare:options:range:locale: with the user’s locale and the following options: NSCaseInsensitiveSearch, NSNumericSearch, NSWidthInsensitiveSearch, and NSForcedOrderingSearch. For an example, see Sorting strings like Finder.

  • 如果要比较字符串以便按照在Finder中显示的方式对它们进行排序,则应使用compare:options:range:locale:使用用户的语言环境和以下选项:NSCaseInsensitiveSearch,NSNumericSearch,NSWidthInsensitiveSearch和NSForcedOrderingSearch。 有关示例,请参阅像Finder一样对字符串进行排序。

Search and Comparison Options

Several of the search and comparison methods take an “options” argument. This is a bit mask that adds further constraints to the operation. You create the mask by combining the following options (not all options are available for every method):

  • 一些搜索和比较方法采用“选项”参数。 这是一个位掩码,为操作添加了进一步的约束。 您可以通过组合以下选项来创建掩码(并非所有选项都适用于每个方法):


    07. Searching, Comparing, and Sorting Strings_第2张图片
    image.png
  1. Ignores case distinctions among characters.
    • 忽略字符之间的区别。
  2. Performs a byte-for-byte comparison. Differing literal sequences (such as composed character sequences) that would otherwise be considered equivalent are considered not to match. Using this option can speed some operations dramatically.
    • 执行逐字节比较。 不同的文字序列(例如组合的字符序列)被认为是等同的被认为是不匹配的。 使用此选项可以显着加快某些操作。
  3. Performs searching from the end of the range toward the beginning.
    • 执行从范围的末尾到开头的搜索。
  4. Performs searching only on characters at the beginning or, if NSBackwardsSearch is also specified, the end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of characters occurs elsewhere in the string.
    • 仅在开头搜索字符,或者如果还指定了NSBackwardsSearch,则搜索范围的结尾。 即使匹配的字符序列出现在字符串的其他位置,开头或结尾也不会发现任何内容。
  5. When used with the compare:options: methods, groups of numbers are treated as a numeric value for the purpose of comparison. For example, Filename9.txt < Filename20.txt < Filename100.txt.
    • 与compare:options:方法一起使用时,为了进行比较,数字组 将被视为数值。 例如,Filename9.txt

Search and comparison are currently performed as if the NSLiteralSearch option were specified.

  • 目前执行搜索和比较,就好像指定了NSLiteralSearch选项一样。

Examples

Case-Insensitive Search for Prefix and Suffix

  • 不区分大小写的前缀和后缀搜索

NSString provides the methods hasPrefix: and hasSuffix: that you can use to find an exact match for a prefix or suffix. The following example illustrates how you can use rangeOfString:options: with a combination of options to perform case insensitive searches.

  • NSString提供方法hasPrefix:和hasSuffix:您可以使用它来查找前缀或后缀的完全匹配。 以下示例说明了如何使用rangeOfString:options:使用选项组合来执行不区分大小写的搜索。
NSString *searchString = @"age";
 
NSString *beginsTest = @"Agencies";
NSRange prefixRange = [beginsTest rangeOfString:searchString
    options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
 
// prefixRange = {0, 3}
 
NSString *endsTest = @"BRICOLAGE";
NSRange suffixRange = [endsTest rangeOfString:searchString
    options:(NSAnchoredSearch | NSCaseInsensitiveSearch | NSBackwardsSearch)];
 
// suffixRange = {6, 3}

Comparing Strings

The following examples illustrate the use of various string comparison methods and associated options. The first shows the simplest comparison method.

  • 以下示例说明了各种字符串比较方法和相关选项的使用。 第一个是最简单的比较方法。
NSString *string1 = @"string1";
NSString *string2 = @"string2";
NSComparisonResult result;
result = [string1 compare:string2];
// result = -1 (NSOrderedAscending)

You can compare strings numerically using the NSNumericSearchoption:

NSString *string10 = @"string10";
NSString *string2 = @"string2";
NSComparisonResult result;
 
result = [string10 compare:string2];
// result = -1 (NSOrderedAscending)
 
result = [string10 compare:string2 options:NSNumericSearch];
// result = 1 (NSOrderedDescending)

You can use convenience methods (caseInsensitiveCompare: and localizedCaseInsensitiveCompare:) to perform case-insensitive comparisons:

  • 您可以使用便捷方法(caseInsensitiveCompare:和localizedCaseInsensitiveCompare :)来执行不区分大小写的比较:
NSString *string_a = @"Aardvark";
NSString *string_A = @"AARDVARK";
 
result = [string_a compare:string_A];
// result = 1 (NSOrderedDescending)
 
result = [string_a caseInsensitiveCompare:string_A];
// result = 0 (NSOrderedSame)
// equivalent to [string_a compare:string_A options:NSCaseInsensitiveSearch]

Sorting strings like Finder

To sort strings the way Finder does in OS X v10.6 and later, use the localizedStandardCompare: method. It should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method is different under different localizations, so clients should not depend on the exact sorting order of the strings.

  • 要按照Finder在OS X v10.6及更高版本中的方式对字符串进行排序,请使用localizedStandardCompare:方法。 只要文件名或其他字符串出现在适合类似Finder的排序的列表和表中,就应该使用它。 在不同的本地化下,此方法的确切行为是不同的,因此客户端不应该依赖于字符串的确切排序顺序。

The following example shows another implementation of similar functionality, comparing strings to order them in the same way as they’re presented in Finder, and it also shows how to sort the array of strings. First, define a sorting function that includes the relevant comparison options (for efficiency, pass the user's locale as the context—this way it's only looked up once).

  • 下面的示例显示了类似功能的另一个实现,比较字符串以与它们在Finder中呈现的方式对它们进行排序,并且还显示了如何对字符串数组进行排序。 首先,定义一个包含相关比较选项的排序函数(为了提高效率,将用户的语言环境作为上下文传递 - 这样只需查看一次)。
int finderSortWithLocale(id string1, id string2, void *locale)
{
    static NSStringCompareOptions comparisonOptions =
        NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
 
    NSRange string1Range = NSMakeRange(0, [string1 length]);
 
    return [string1 compare:string2
                    options:comparisonOptions
                    range:string1Range
                    locale:(NSLocale *)locale];
}

You pass the function as a parameter to sortedArrayUsingFunction:context: with the user’s current locale as the context:

  • 将函数作为参数传递给sortedArrayUsingFunction:context:将用户的当前语言环境作为上下文:
NSArray *stringsArray = @[@"string 1",
                          @"String 21",
                          @"string 12",
                          @"String 11",
                          @"String 02"];
 
NSArray *sortedArray = [stringsArray sortedArrayUsingFunction:finderSortWithLocale
                                     context:[NSLocale currentLocale]];
 
// sortedArray contains { "string 1", "String 02", "String 11", "string 12", "String 21" }

你可能感兴趣的:(07. Searching, Comparing, and Sorting Strings)