开发者

Count how many times string occurs in another string

开发者 https://www.devze.com 2023-02-12 15:08 出处:网络
Is there any wa开发者_运维技巧y of counting how many times one string occurs in another. Eg. how many times does \"/\" appear in \"bla/hsi/sgg/shrgsvs/\"= 4.You could do:

Is there any wa开发者_运维技巧y of counting how many times one string occurs in another. Eg. how many times does "/" appear in "bla/hsi/sgg/shrgsvs/"= 4.


You could do:

NSArray *a = [myString componentsSeparatedByString:@"/"];
int i = [a count] - 1;

But that's really quick and dirty. Someone else might come up with a better answer shortly.

EDIT:

Now that I think about it, this might work too:

NSUInteger count = 0;
NSUInteger length = [str length];

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

Although I still think there's gotta be a better way...

0

精彩评论

暂无评论...
验证码 换一张
取 消