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

版本记录

版本号 时间
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".

后记

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

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

推荐阅读更多精彩内容