NSString 中子字符串的出现次数? [英] Number of occurrences of a substring in an NSString?

查看:28
本文介绍了NSString 中子字符串的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 NSString(例如,@"cake")在较大的 NSString(例如,@"Cheesecake, apple cake, and cherry馅饼")?

How can I get the number of times an NSString (for example, @"cake") appears in a larger NSString (for example, @"Cheesecake, apple cake, and cherry pie")?

我需要对很多字符串执行此操作,因此无论我使用什么方法都需要相对较快.

I need to do this on a lot of strings, so whatever method I use would need to be relatively fast.

谢谢!

推荐答案

这没有经过测试,但应该是一个好的开始.

This isn't tested, but should be a good start.

NSUInteger count = 0, length = [str length];
NSRange range = NSMakeRange(0, length); 
while(range.location != NSNotFound)
{
  range = [str rangeOfString: @"cake" options:0 range:range];
  if(range.location != NSNotFound)
  {
    range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
    count++; 
  }
}

这篇关于NSString 中子字符串的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆