0

Is there any way of counting how many times one string occurs in another. Eg. how many times does "/" appear in "bla/hsi/sgg/shrgsvs/"= 4.

Seb Jachec
  • 3,003
  • 2
  • 30
  • 56

1 Answers1

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...

Aurum Aquila
  • 9,126
  • 4
  • 25
  • 24
  • I think it should be a.count - 1. (there are 5 components separated by 4 slashes – Meta-Knight Feb 21 '11 at 15:08
  • @Meta-Knight Yes, for the first solution that's probably correct. I've edited my answer. Also note that `[NSArray count]` is not the same as `NSArray.count`. I don't think that `NSArray` actually has any properties. – Aurum Aquila Feb 21 '11 at 15:13
  • You wouldn't call `[NSArray count]` because `count` is an instance method not a class method. And dot syntax on Objective-C instances is just syntactic sugar for calling that method with brackets; thus `array.count` is equivalent to `[array count]`. However I'd always argue against using dot syntax for non-properties because it might lead to confusion about what's a property and what isn't. – Alex Rozanski Feb 21 '11 at 15:27
  • @Perspx Yeah, I know that you wouldn't do `[NSArray count]`. I just feel like it makes more sense than typing '`[myArray count]`'. And I did not know that you could call those kinds of methods with dot syntax. That is confusing.... – Aurum Aquila Feb 21 '11 at 15:31