美文网首页
ios中字符串中包含某个字符串的个数

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

作者: mr_ios_zhang | 来源:发表于2022-02-21 17:46 被阅读0次

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

    • (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中字符串中包含某个字符串的个数

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