Hello I try to convert my java function in objective-c for iphone
Java:
public int substrCount(String str, String needle) {
int count = 0;
int index = -needle.length();
while ((index = str.indexOf(needle, index + needle.length())) != -1) {
count++;
}
return count;
}
Iphone:
-(int)substrCount:(NSString *) str withSearch:(NSString *) needle
{
NSRange lastIndex;
lastIndex.length = [str length];
NSInteger count =0;
while(lastIndex.length != -1){
lastIndex = [str rangeOfString:needle options:NSCaseInsensitiveSearch range:lastIndex];
//lastIndex = str.indexOf(needle,lastIndex);
if( lastIndex.length != -1){
NSLog(@"+1");
count ++;
}
}
}
But it’s so hard, I don’t understand when I can make it.
Maybe there are better solution existing? I don’t have found anything :/
Sorry for my bad english !
I’d probably never write this code in production, but You could simply ask:
[[str1 componentsSeparatedByString:str2] count] – 1;
The result of that expression will be an integer representing the number of times
str2was found instr1.However, the problem with your code is rangeOfString: returns
NSNotFoundif it can’t find the substring, not-1.