美文网首页基础知识拾遗
NSString简单细说(十一)—— 字符串的查找

NSString简单细说(十一)—— 字符串的查找

作者: 刀客传奇 | 来源:发表于2017-05-19 01:32 被阅读104次

    版本记录

    版本号 时间
    V1.0 2017.05.18

    前言

    前面我简单的写了些NSString的初始化,写了几篇,都不难,但是可以对新手有一定的小帮助,对于大神级人物可以略过这几篇,NSString本来就没有难的,都是细枝末节,忘记了查一下就会了,没有技术难点,下面我们继续~~~
    1. NSString简单细说(一)—— NSString整体架构
    2. NSString简单细说(二)—— NSString的初始化
    3. NSString简单细说(三)—— NSString初始化
    4. NSString简单细说(四)—— 从URL初始化
    5. NSString简单细说(五)—— 向文件或者URL写入
    6. NSString简单细说(六)—— 字符串的长度
    7. NSString简单细说(七)—— 与C字符串的转化
    8. NSString简单细说(八)—— 识别和比较字符串
    9. NSString简单细说(九)—— 字符串的合并
    10. NSString简单细说(十)—— 字符串的分解

    字符串的查找

    一、- (BOOL)containsString:(NSString *)str;

    看代码

        /**
         * 1. - (BOOL)containsString:(NSString *)str;;
         *
         *  @param str:The string to search for. This value must not be nil.
         *
         *  @return :YES if the receiver contains str, otherwise NO.
         *
         */
        
        NSString *testStr = @"AAAasdWIU";
        BOOL isContain = [testStr containsString:@"asd"];
        NSLog(@"%d--isContain",isContain);
        BOOL isContain1 = [testStr containsString:@"asD"];
        NSLog(@"%d--isContain1",isContain1);
    

    看结果

    2017-05-18 22:52:39.361 NSString你会用吗?[984:24027] 1--isContain
    2017-05-18 22:52:39.361 NSString你会用吗?[984:24027] 0--isContain1
    
    

    结论:从上面可以看到:

    • 这个包含的判断是有大小写之分的,也就是casesensitive的。
    • 这个方法其实和rangeOfString:options: 方法中不传option的时候是等价的。
    • 当用于和用户端呈现的时候需要使用localizedStandardContainsString: 或者localizedCaseInsensitiveContainsString: 方法。

    二、- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;

    先看代码

        /**
         * 2. - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;
         *
         *  @param str:The string to search for. This value must not be nil.
         *
         *  @return :YES if the receiver contains str, otherwise NO.
         *
         */
        
        NSString *testStr = @"AAAasdWIU";
        BOOL isContain = [testStr localizedCaseInsensitiveContainsString:@"asd"];
        NSLog(@"%d--isContain",isContain);
        BOOL isContain1 = [testStr localizedCaseInsensitiveContainsString:@"asD"];
        NSLog(@"%d--isContain",isContain1);
    

    看结果

    2017-05-18 23:04:13.618 NSString你会用吗?[1138:32102] 1--isContain
    2017-05-18 23:04:13.618 NSString你会用吗?[1138:32102] 1--isContain
    
    

    结论:由上可知:

    • 这个是不区分大小写的,也就是说是CaseInsensitive的。

    三、- (BOOL)localizedStandardContainsString:(NSString *)str;

    看代码

        /**
         * 3. - (BOOL)localizedStandardContainsString:(NSString *)str;
         *
         *  @param str:The string to search for. This value must not be nil.
         *
         *  @return :YES if the receiver contains str, otherwise NO.
         *
         */
    
        NSString *testStr = @"AAAasdWIU";
        BOOL isContain = [testStr localizedStandardContainsString:@"asd"];
        NSLog(@"%d--isContain",isContain);
        BOOL isContain1 = [testStr localizedStandardContainsString:@"asD"];
        NSLog(@"%d--isContain",isContain1);
    
    

    看结果

    2017-05-18 23:14:39.764 NSString你会用吗?[1285:42492] 1--isContain
    2017-05-18 23:14:39.764 NSString你会用吗?[1285:42492] 1--isContain
    
    

    结论:这个方法也是不缺分大小写字母的。


    四、- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;

    看代码

    
        /**
         * 4. - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;
         *
         *  @param searchSet:A character set. This value must not be nil.
         *
         *  @return :The range in the receiver of the first character found from aSet. Returns a range of {NSNotFound, 0} if none of the characters in aSet are found.    
         *
         */
        
        NSString *testStr = @"AAAasdWIU";
        NSCharacterSet *characterSet = [NSCharacterSet lowercaseLetterCharacterSet];
        NSRange range = [testStr rangeOfCharacterFromSet:characterSet];
        NSLog(@"range--location=%ld--lengh=%ld",range.location,range.length);
        
        NSCharacterSet *characterSet1 = [NSCharacterSet uppercaseLetterCharacterSet];
        NSRange range1 = [testStr rangeOfCharacterFromSet:characterSet1];
        NSLog(@"range1--location=%ld--lengh=%ld",range1.location,range1.length);
    
    
    

    看结果

    2017-05-18 23:26:24.941 NSString你会用吗?[1457:52949] range--location=3--lengh=1
    2017-05-18 23:26:24.941 NSString你会用吗?[1457:52949] range1--location=0--lengh=1
    
    

    结论:由上可知:

    • 这个方法的作用就是找到character所对应的range。
    • searchSet不能为空,如为空就会抛出异常NSInvalidArgumentException。
    • 如果找不到就会返回结果{NSNotFound, 0}。
    • 这个方法和 rangeOfCharacterFromSet:options:中options为nil时是一样的。

    五、- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask;

    看代码

        /**
         * 5. - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask;
         *
         *  @param searchSet:A character set. This value must not be nil.
         *  @param mask:A character set. This value must not be nil.
         *
         *  @return :A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSAnchoredSearch, NSBackwardsSearch.
         *
         */
        
        NSString *testStr = @"AAasdWIU";
        NSCharacterSet *characterSet = [NSCharacterSet lowercaseLetterCharacterSet];
        NSRange range = [testStr rangeOfCharacterFromSet:characterSet options:NSBackwardsSearch];
        NSLog(@"range--location=%ld--lengh=%ld",range.location,range.length);
        
        NSCharacterSet *characterSet1 = [NSCharacterSet uppercaseLetterCharacterSet];
        NSRange range1 = [testStr rangeOfCharacterFromSet:characterSet1 options:NSLiteralSearch];
        NSLog(@"range1--location=%ld--lengh=%ld",range1.location,range1.length);
    
    

    看结果

    2017-05-18 23:50:38.672 NSString你会用吗?[1696:69877] range--location=4--lengh=1
    2017-05-18 23:50:38.672 NSString你会用吗?[1696:69877] range1--location=0--lengh=1
    
    
    

    结论:由上可知

    • searchSet为空则会抛出异常。
    • 这个方法可以看做方法rangeOfCharacterFromSet:options:range:,range为整个字符串的特例。

    六、- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;

    看代码

        /**
         * 6. - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
         *
         *  @param searchSet:A character set. This value must not be nil.
         *  @param mask:A character set. This value must not be nil.
         *  @param rangeOfReceiverToSearch:A character set. This value must not be nil.
         *
         *  @return :The range in the receiver of the first character found from aSet within aRange. Returns a range of {NSNotFound, 0} if none of the characters in aSet are found.
         *
         */
        
        NSString *testStr = @"2AasdWAI3U";
        NSCharacterSet *characterSet = [NSCharacterSet uppercaseLetterCharacterSet];
        NSRange strRange = NSMakeRange(0, 4);
        NSRange range = [testStr rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch range:strRange];
        NSLog(@"range--location=%ld--lengh=%ld",range.location,range.length);
    
    

    看结果

    2017-05-19 00:04:17.438 NSString你会用吗?[1885:80771] range--location=1--lengh=1
    
    

    结论:这里需要注意这个例子

    • searching the string “strüdel”—containing the decomposed characters “u” (U+0075 LATIN SMALL LETTER U) and “¨” (U+0308 COMBINING DIAERESIS)—with a character set containing the precomposed character “ü” (U+00FC LATIN SMALL LETTER U WITH DIAERESIS) would return the range {NSNotFound, 0}, because none of the characters in the set are found.

    七、- (NSRange)rangeOfString:(NSString *)searchString;

    看代码

        /**
         * 7. - (NSRange)rangeOfString:(NSString *)searchString;
         *
         *  @param searchString:The string to search for.
         *
         *  @return :An NSRange structure giving the location and length in the receiver of the first occurrence of searchString.Returns {NSNotFound, 0} if searchString is not found or is empty ("").
         
         *
         */
    
        NSString *testStr = @"2AasdWAI3U";
        NSRange range = [testStr rangeOfString:@"as"];
        NSLog(@"range--location=%ld--lengh=%ld",range.location,range.length);
    
    

    看结果

    2017-05-19 00:12:35.795 NSString你会用吗?[1975:86532] range--location=2--lengh=2
    
    

    结论:由此可知

    • NSString对象的比较都是检查它们的点序列的unicode是否相等,所以返回的searchString的区间range是不同的。所以字符序列相等的字符串也可能长度是不同的。
    • 当要呈现给用户的时候,用这个方法localizedStandardRangeOfString:。

    八、- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;

    看代码

        /**
         * 8. - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
         *
         *  @param searchString:The string to search for.
         *  @param mask:A mask specifying search options. For possible values, see NSStringCompareOptions.
         *
         *  @return :An NSRange structure giving the location and length in the receiver of the first occurrence of searchString.Returns {NSNotFound, 0} if searchString is not found or is empty ("").
         
         *
         */
        
        NSString *testStr = @"2AasdWAI3U";
        NSRange range = [testStr rangeOfString:@"2" options:NSNumericSearch];
        NSLog(@"range--location=%ld--lengh=%ld",range.location,range.length);
    
    

    看结果

    2017-05-19 00:27:03.481 NSString你会用吗?[2205:98656] range--location=0--lengh=1
    
    

    结论:这个很简单,就不多说了。


    九、- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;

    看代码

        /**
         * 9. - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
         *
         *  @param searchString:The string to search for.
         *  @param mask:A mask specifying search options. For possible values, see NSStringCompareOptions.
         *  @param rangeOfReceiverToSearch:The range within the receiver for which to search for aString.Raises an NSRangeException if rangeOfReceiverToSearch is invalid.
         *
         *  @return :An NSRange structure giving the location and length in the receiver of searchString
         within rangeOfReceiverToSearch in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {NSNotFound, 0} if searchString is not found or is empty ("").
         *
         */
        
        NSString *testStr = @"2AasdWAI3U";
        NSRange range = NSMakeRange(0, 4);
        NSRange range1 = [testStr rangeOfString:@"3" options:NSNumericSearch range:range];
        NSLog(@"range1--location=%ld--lengh=%ld",range1.location,range1.length);
    
    
    

    看结果

    2017-05-19 00:34:17.048 NSString你会用吗?[2301:104399] range1--location=9223372036854775807--lengh=0
    
    
    

    结论:这个很简单。当要呈现给用户的时候,应该使用方法localizedStandardRangeOfString:


    十、- (NSRange)rangeOfString:(NSString ***)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(NSLocale **)locale;

    这个方法参数比较多,先看一下参数配置吧。

    参数配置

    看代码

        /**
         * 10. - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(NSLocale *)locale;
         *
         *  @param searchString:The string to search for.
         *  @param mask:A mask specifying search options. For possible values, see NSStringCompareOptions.
         *  @param rangeOfReceiverToSearch:The range within the receiver for which to search for aString.Raises an NSRangeException if rangeOfReceiverToSearch is invalid.
         *  @param locale:The locale to use when comparing the receiver with aString. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.
         The locale argument affects the equality checking algorithm. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (U+0131 LATIN SMALL DOTLESS I), not the normal “i” character.
    
         *
         *  @return :An NSRange structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {NSNotFound, 0} if aString is not found or is empty ("").
         *
         */
    
        NSString *testStr = @"2AasdWAI3U";
        NSRange range = NSMakeRange(0, 4);
        NSRange range1 = [testStr rangeOfString:@"3" options:NSNumericSearch range:range locale:nil];
        NSLog(@"range1--location=%ld--lengh=%ld",range1.location,range1.length);
    

    看结果

    2017-05-19 00:44:22.482 NSString你会用吗?[2422:112275] range1--location=9223372036854775807--lengh=0
    
    

    结论:自己看代码和过程。当呈现给用户时,要使用下面这个方法 localizedStandardRangeOfString:


    十一、- (NSRange)localizedStandardRangeOfString:(NSString *)str;

    看代码

        /**
         * 11. - (NSRange)localizedStandardRangeOfString:(NSString *)str;
         *
         *  @param str:The string to search for. This value must not be nil.
         *
         *  @return :An NSRange structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {NSNotFound, 0} if aString is not found or is empty ("").
         *
         */
        
        NSString *testStr = @"2AasdWAI3U";
        NSRange range1 = [testStr localizedStandardRangeOfString:@"aa"];
        NSLog(@"range1--location=%ld--lengh=%ld",range1.location,range1.length);
    
    

    看结果

    2017-05-19 00:50:58.881 NSString你会用吗?[2520:117628] range1--location=1--lengh=2
    
    

    结论:这里的比较就是不区分大小写字母的比较。


    十二、- (void)enumerateLinesUsingBlock:(void (^)(NSString **line, BOOL ***stop))block;

    这个方法其实就是枚举器的使用,数组和字典都有这个类似方法。这个方法与 (for(... in ...)在效率上基本一致,有时会快些我们先看一下block这个参数

    block参数

    我们先准备个文件

    准备文件

    看代码

        /**
         * 12. - (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block;
         *
         *  @param block:The block executed for the enumeration.The block takes two arguments:
         *
         */
        
        //字符串
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
        NSString *fileStr = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
        
        //一行一行的读取
        [fileStr enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {
            
            NSLog(@"%@---line",line);
            
        }];
    
    

    看结果

    2017-05-19 01:03:16.160 NSString你会用吗?[2780:127173] AASsswj1wjihoi`w`9897298`7298`2@&#&%#*(&)!&)!AASsswj---line
    2017-05-19 01:03:16.160 NSString你会用吗?[2780:127173] 1wjihoi`w`9897298`7298`2@&#&%#*(&)!&)!---line
    
    

    结论:枚举器的使用。


    十三、- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString **substring, NSRange substringRange, NSRange enclosingRange, BOOL ***stop))block;

    看参数,如下图

    枚举参数

    这里还有个枚举值NSStringEnumerationOptions

    typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
        // Pass in one of the "By" options:
        NSStringEnumerationByLines = 0,                       // Equivalent to lineRangeForRange:
        NSStringEnumerationByParagraphs = 1,                  // Equivalent to paragraphRangeForRange:
        NSStringEnumerationByComposedCharacterSequences = 2,  // Equivalent to rangeOfComposedCharacterSequencesForRange:
        NSStringEnumerationByWords = 3,
        NSStringEnumerationBySentences = 4,
        // ...and combine any of the desired additional options:
        NSStringEnumerationReverse = 1UL << 8,
        NSStringEnumerationSubstringNotRequired = 1UL << 9,
        NSStringEnumerationLocalized = 1UL << 10              // User's default locale
    };
    
    

    看代码

        /**
         * 13. - (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block;
         *
         *  @param range:The range within the string to enumerate substrings.
         *  @param opts:Options specifying types of substrings and enumeration styles.
         *  @param block:The block executed for the enumeration.The block takes four arguments.
         *
         */
        
        //字符串
        NSString *fileStr = @"212ehohgivieye0ohsoIFIFUFYDST";
        NSRange range = NSMakeRange(0, 10);
        
        //一个字符一字符的读取
        [fileStr enumerateSubstringsInRange:range options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
            NSLog(@"%@--substring",substring);
        }];
    
    

    看结果

    2017-05-19 01:22:41.689 NSString你会用吗?[3266:146676] 212ehohgiv--substring
    
    

    结论:需要注意

    • If this method is sent to an instance of NSMutableString, mutation (deletion, addition, or change) is allowed, as long as it is within enclosingRange. After a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator assumes any change in length occurs in the specified range.)
    • For example, if the block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range. This is the case even if mutation of the previous range changes the string in such a way that the following substring would have extended to include the already enumerated range. For example, if the string "Hello World" is enumerated via words, and the block changes "Hello " to "Hello", thus forming "HelloWorld", the next enumeration will return "World" rather than "HelloWorld".

    后记

    很晚了,睡觉了。待续~~~~~

    花海

    相关文章

      网友评论

        本文标题:NSString简单细说(十一)—— 字符串的查找

        本文链接:https://www.haomeiwen.com/subject/jxijxxtx.html