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:

  • 这些是基本的搜索和比较方法:
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):

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


    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 <Filename20.txt <Filename100.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" }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,128评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,316评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,737评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,283评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,384评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,458评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,467评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,251评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,688评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,980评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,155评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,818评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,492评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,142评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,382评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,020评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,044评论 2 352

推荐阅读更多精彩内容