字符串中子字符串的出现次数

时间:2011-10-16 17:07:32

标签: objective-c c string

这是查找子字符串出现次数的可接受方式吗?可以提高效率吗?应该使用什么编码从NSString转到c字符串?

我不是100%肯定while语句中的()!=NULL,它似乎工作正常,当找不到更多的事件时,它确实打破了while循环。

- (NSUInteger)occurenceOfString:(NSString *)substring {
    const char *substr = [substring cStringUsingEncoding:NSUTF8StringEncoding];
    const char *selfstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    unsigned long substrlen = strlen(substr);
    NSUInteger count = 0;
    char * ptr;
    while ((ptr = strstr(selfstr, substr)) != NULL && substr != '\0') {
        count++;
        substr += substrlen + *ptr;
    }
    return count;
}

(这是一种类别方法,所以在自己中搜索字符串。)

1 个答案:

答案 0 :(得分:8)

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