Skip to content

Searching, Comparing, and Sorting Strings

binism edited this page Mar 20, 2016 · 11 revisions

Searching, Comparing, and Sorting Strings

字符串的搜索、比较、排序

字符串对象提供了多种查找字符或者子串、字符串之间的比较方法。这些方法一直按照Unicode标准来判断两个字符序列是否是等价的。字符串类提供比较方法,这些方法能够妥善处理字符序列的组成,当然,如果效率十分重要的情况下,你也可以选择指定的字面搜索。(The string classes provide comparison methods that 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.)

(字符串对象)查找和比较的方法

(字符串)查找和比较有很多不同变体。最简单的一种是对整个字符串进行查找和比较。其它变型允许你改变方式来对字符序列的执行比较,并进行搜索或比较字符串中特定范围指定的字符; (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; )在给定的(编码)环境下,也能进行字符串查找和比较。 这里是一些基本的查找和比较方式:

Search methods Comparison
rangeOfString: compare:
rangeOfString:options: compare:options:
rangeOfString:options:range: compare:options:range:
rangeOfString:options:range:locale: compare:options:range:locale:
rangeOfCharacterFromSet:
rangeOfCharacterFromSet:options:
rangeOfCharacterFromSet:options:range:

字符串搜索

使用````rangeOfString:...来在一个给定字符串中查找子串。rangeOfCharacterFromSet:...```方法来从指定字符集中查找单个的字符。仅当一个子串完全被包含在一个特定的序列中,它可被发现。不使用```NSLiteralSearch```方法(见下)或者指定一个序列的范围去做搜索或比较,这一段序列范围不能超过字符序列的两端;若超过了字符序列的两端,你将得到不正确的结果。(参见```rangeOfComposedCharacterSequenceAtIndex:```方法介绍:一个调整指定范围使其恰好落在字符序列的边界上。)

你可以使用NSString的一个实例来对一个数值的、字符的字符串对象来进行读入。scannner的更多信息,参见Scanners。NSSstring和NSString类都使用NSCharacterSet类来做搜索操作。字符集(character set)的更多信息,参见Character Set。 若简单地判断一个字符串是否包含一个给定的式样(pattern),使用predicate:

BOOL match = [myPredicate evaluateWithObject:myString];

predicate的更多信息,参见Predicate Programming Guide。

字符串比较与排序

compare:... 方法的返回值是所给字符串的字母序。其他的几种方法可以让你判断两个字符串是否是相等的、或者一个是否是另一个的前缀或字串,但是它们没有可以让你指定搜索选项或搜索范围的变体。

最简单的字符串比较方法是compare:这是compare:options:range:的一种援引方式,不带选项(option)范围是给定字符串宽度的全部范围。如果想使用带选项(NSCaseInsensitiveSearch, NSLiteralSearch, or NSNumericSearch)的比较,可使用compare:options:;如果还想指定(比较)的范围,可使用compare:options:range:locale:。NSString也同样提供多种不指定范围和选项的直接比较方法,例如caseInsensitiveCompare:和localizedCompare:。

重要提示:对用户可见的排序列表,你应该使用本地化的比较,你应该使用localizedCompare:和localizedCaseInsensitiveCompare:而不是compare:和caseInsensitiveCompare:。

如果您想要比较的字符串,命令他们以Finder中的排序方式来展示(If you want to compare strings to order them in the same way as they’re presented in Finder,),你应该使用compare:options:range:locale:加上使用者的(编码)环境和以下选项:NSCaseInsensitiveSearch、NSNumericSearch、NSWidthInsensitiveSearch、NSForcedOrderingSearch。例如:[Sorting strings like Finder](Sorting strings like Finder)。

搜索和比较选项

有几种(字符串)搜索和比较方法含有一个“options”参数。这是一个对(搜索、比较)操作添加进一步的约束的位掩码(bit mask)。可以通过组合以下的选项来创建掩码(mask)。(一些选项对于某些方法不适用(not all options are available for every method)):

Search opion Effect
NSCaseInsensitiveSearch Ignores case distinctions among characters
NSLiteralSearch 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.
NSBackwardsSearch Performs searching from the end of the range toward the beginning.
NSAnchoredSearch 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.
NSNumericSearch 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.

若NSLiteralSearch被指定,搜索和比较将会按照当前的(设置)来执行。

例子

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

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}

比较字符串

下面几个例子介绍了字符串比较方法的几种用法和一些相关的选项。第一个例子展示了最简单的字符串比较方法。

NSString *string1 = @"string1";
NSString *string2 = @"string2";
NSComparisonResult result;
result = [string1 compare:string2];
// result = -1 (NSOrderedAscending)

可以利用NSNumericSearch选项来对字符串进行数值化比较:

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

方便地利用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]

像Finder一样排序字符串

使用localizedStandardCompare:来像Finder(OS X 10.6及以后的版本)一样排序字符串。无论是按照文件名还是其它的一些字符串,像Finder那样把对象排序成一个列表的做法是普遍适用的。此方法在不同环境下具体行为是不一样的,所以客户不应该依赖于字符串的确切顺序排序。

下面的例子展示了一个相似的函数功能,它能比较字符串并使用与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];
}

把这个函数当作一个参数,将这个参数传递给sortedArrayUsingFunction:context:,并将用户字符串当作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" }

Clone this wiki locally