Apple开发_计算一个字符串中包含几个目标子字符串

功能代码

// 计算一个字符串中包含几个目标子字符串
- (NSInteger)count_Of:(NSString *)main_string Sub_String:(NSString *)sub_string {
    NSInteger count = 0;
    if ([main_string containsString:sub_string]) {
        count ++;
        NSRange ns_range = [main_string rangeOfString:sub_string];
        main_string = [main_string substringFromIndex:ns_range.location + ns_range.length];
        count += [self count_Of:main_string Sub_String:sub_string];
    }
    return count;
}

测试

NSString *main_string = @"000012345\n6789000\n";
NSString *sub_string = @"\n";
NSInteger count = [self count_Of:main_string Sub_String:sub_string];
GCLog(@"count == %@", @(count));

结果

posted @ 2022-05-10 11:05  CH520  阅读(62)  评论(0编辑  收藏  举报