ios中字符串中包含某个字符串的个数

//循环方法
///核心思想是找到相同字符串就对字符串进行截取,然后对剩余字符串进行

  • (NSInteger)getCountFrom:(NSString)allStr with:(NSString)cutStr{
    //空的时候直接返回0
    if (allStr.length == 0) {
    return 0;
    }
    //接下来是处理字符串
    NSString *leftStr = allStr;
    NSInteger includeCount = 0;
    //显得我严谨,其实这里循环条件无所谓
    while (leftStr.length >= cutStr.length) {
    NSRange range = [leftStr rangeOfString:cutStr];
    if (range.location != NSNotFound) {
    includeCount += 1;
    leftStr = [leftStr substringFromIndex:range.location + range.length];
    }else{
    return includeCount;
    }
    }
    return includeCount;
    }

//递归方法
///核心思想是找到相同字符串就对字符串进行截取,然后对剩余字符串进行

  • (NSInteger)getCountFrom1:(NSString)allStr with:(NSString)cutStr{
    static NSInteger includeCount = 0;
    //直接处理字符串
    if (allStr.length < cutStr.length) {
    return includeCount;
    }
    NSRange range = [allStr rangeOfString:cutStr];
    if (range.location != NSNotFound) {
    includeCount += 1;
    [self getCountFrom1:[allStr substringFromIndex:range.location + range.length] with:cutStr];
    }else{
    return includeCount;
    }
    return includeCount;
    }

你可能感兴趣的:(ios中字符串中包含某个字符串的个数)