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.

  • 字符串類提供了在字符串中查找字符和子字符串以及將一個(gè)字符串與另一個(gè)字符串進(jìn)行比較的方法。 這些方法符合Unicode標(biāo)準(zhǔn),用于確定兩個(gè)字符序列是否相同。 字符串類提供了正確處理組合字符序列的比較方法,盡管您可以選擇在效率很重要時(shí)指定文字搜索,并且可以保證組合字符序列的某些規(guī)范形式。

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.

  • 搜索和比較方法分別有幾種變體。 每個(gè)最簡(jiǎn)單的版本搜索或比較整個(gè)字符串。 其他變體允許您更改組合字符序列的比較方式,并指定要搜索或比較的字符串中的特定字符范圍; 您還可以在給定語言環(huán)境的上下文中搜索和比較字符串。

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:...方法從提供的字符集中搜索單個(gè)字符。

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.)

  • 僅在完全包含在指定范圍內(nèi)時(shí)才會(huì)找到子字符串。 如果為搜索或比較方法指定范圍而不請(qǐng)求NSLiteralSearch(見下文),則范圍不得破壞任何一端的組合字符序列; 如果是這樣,你可能得到一個(gè)不正確的結(jié)果。 (請(qǐng)參閱rangeOfComposedCharacterSequenceAtIndex的方法說明:以獲取將范圍調(diào)整為位于字符序列邊界上的代碼示例。)

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實(shí)例掃描字符串對(duì)象的數(shù)值和字符串值。 有關(guān)掃描儀的更多信息,請(qǐng)參閱掃描儀。 NSString和NSScanner類集群都使用NSCharacterSet類集群進(jìn)行搜索操作。 有關(guān)字符集的更多信息,請(qǐng)參閱字符集。

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.

  • 有關(guān)謂詞的更多信息,請(qǐng)參閱謂詞編程指南。

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:...方法返回接收者的詞法排序和提供的字符串。 其他幾種方法允許您確定兩個(gè)字符串是否相等,或者一個(gè)是否是另一個(gè)字符串的前綴或后綴,但它們沒有允許您指定搜索選項(xiàng)或范圍的變體。

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:.

  • 比較字符串的最簡(jiǎn)單方法是比較: - 這與調(diào)用compare相同:options:range:沒有選項(xiàng),接收者的完整范圍作為范圍。 如果要指定比較選項(xiàng)(NSCaseInsensitiveSearch,NSLiteralSearch或NSNumericSearch),可以使用compare:options:; 如果要指定區(qū)域設(shè)置,可以使用compare:options:range:locale:。 NSString還提供了各種便捷方法,允許您執(zhí)行常見的比較,而無需直接指定范圍和選項(xiàng),例如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:.

  • 重要說明:對(duì)于用戶可見的排序列表,應(yīng)始終使用本地化比較。 因此,通常不使用compare:或caseInsensitiveCompare:您應(yīng)該使用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中顯示的方式對(duì)它們進(jìn)行排序,則應(yīng)使用compare:options:range:locale:使用用戶的語言環(huán)境和以下選項(xiàng):NSCaseInsensitiveSearch,NSNumericSearch,NSWidthInsensitiveSearch和NSForcedOrderingSearch。 有關(guān)示例,請(qǐng)參閱像Finder一樣對(duì)字符串進(jìn)行排序。

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):

  • 一些搜索和比較方法采用“選項(xiàng)”參數(shù)。 這是一個(gè)位掩碼,為操作添加了進(jìn)一步的約束。 您可以通過組合以下選項(xiàng)來創(chuàng)建掩碼(并非所有選項(xiàng)都適用于每個(gè)方法):


    image.png
  1. Ignores case distinctions among characters.
    • 忽略字符之間的區(qū)別。
  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.
    • 執(zhí)行逐字節(jié)比較。 不同的文字序列(例如組合的字符序列)被認(rèn)為是等同的被認(rèn)為是不匹配的。 使用此選項(xiàng)可以顯著加快某些操作。
  3. Performs searching from the end of the range toward the beginning.
    • 執(zhí)行從范圍的末尾到開頭的搜索。
  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,則搜索范圍的結(jié)尾。 即使匹配的字符序列出現(xiàn)在字符串的其他位置,開頭或結(jié)尾也不會(huì)發(fā)現(xiàn)任何內(nèi)容。
  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:方法一起使用時(shí),為了進(jìn)行比較,數(shù)字組 將被視為數(shù)值。 例如,F(xiàn)ilename9.txt <Filename20.txt <Filename100.txt。

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

  • 目前執(zhí)行搜索和比較,就好像指定了NSLiteralSearch選項(xiàng)一樣。

Examples

Case-Insensitive Search for Prefix and Suffix

  • 不區(qū)分大小寫的前綴和后綴搜索

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:使用選項(xiàng)組合來執(zhí)行不區(qū)分大小寫的搜索。
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.

  • 以下示例說明了各種字符串比較方法和相關(guān)選項(xiàng)的使用。 第一個(gè)是最簡(jiǎn)單的比較方法。
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 :)來執(zhí)行不區(qū)分大小寫的比較:
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及更高版本中的方式對(duì)字符串進(jìn)行排序,請(qǐng)使用localizedStandardCompare:方法。 只要文件名或其他字符串出現(xiàn)在適合類似Finder的排序的列表和表中,就應(yīng)該使用它。 在不同的本地化下,此方法的確切行為是不同的,因此客戶端不應(yīng)該依賴于字符串的確切排序順序。

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).

  • 下面的示例顯示了類似功能的另一個(gè)實(shí)現(xiàn),比較字符串以與它們?cè)贔inder中呈現(xiàn)的方式對(duì)它們進(jìn)行排序,并且還顯示了如何對(duì)字符串?dāng)?shù)組進(jìn)行排序。 首先,定義一個(gè)包含相關(guān)比較選項(xiàng)的排序函數(shù)(為了提高效率,將用戶的語言環(huán)境作為上下文傳遞 - 這樣只需查看一次)。
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:

  • 將函數(shù)作為參數(shù)傳遞給sortedArrayUsingFunction:context:將用戶的當(dāng)前語言環(huán)境作為上下文:
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" }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評(píng)論 0 10
  • 從來沒有提筆畫過,剛剛開始學(xué)習(xí)只能獻(xiàn)丑等待老師的點(diǎn)評(píng)和教導(dǎo)
    漫步liu閱讀 152評(píng)論 0 0
  • 人生就好比一場(chǎng)長(zhǎng)途旅行,而你自己是這趟列車的車長(zhǎng)。在這趟旅途中,你會(huì)遇到很多停靠的站點(diǎn),有的站點(diǎn)很大,有點(diǎn)很小,就...
    木槿女孩閱讀 4,966評(píng)論 0 2
  • 人活一世,難免有些尷尬,最讓你覺得無奈的,或許就是借錢,有的人借錢,會(huì)說到做到,即使到時(shí)候還不出來,也會(huì)想出辦法還...
    洋芋土豆馬鈴薯閱讀 435評(píng)論 0 0
  • 昨天,在便簽紙上寫道:明天一定要把《末代皇帝》看了,并狠狠的貼在墻上,今兒下載好發(fā)現(xiàn)近四個(gè)小時(shí),動(dòng)也沒動(dòng)。我像之前...
    坤泉理財(cái)閱讀 182評(píng)論 0 0

友情鏈接更多精彩內(nèi)容