我想计算我的NSString的NSArray对象。我的NSArray有@"a"
,@"w"
个对象,我的字符串是@"abcdefgw"
。我想知道我的字符串中有@"w"
个对象的次数。
答案 0 :(得分:2)
您可以使用- (NSArray *)componentsSeparatedByString:(NSString *)separator
,但这可能存在边界问题。你也可以像这样使用stringByReplacingOccurrencesOfString:withString:
:
NSString *shortString = [myString stringByReplacingOccurrencesOfString:@"w" withString:@""];
return mystring.length-shortString.length;
答案 1 :(得分:0)
如果您想要计算子字符串,则必须搜索子字符串,然后每次缩小范围......类似于。
-(NSInteger)occurrencesOfSubstring:(NSString *)substring inString:(NSString *)string
{
int occurrences =0;
NSRange searchRange = NSMakeRange(0, [string length]);
NSRange foundRange;
do {
foundRange = [string rangeOfString:substring options:NSCaseInsensitiveSearch range:searchRange];
if ((foundRange.location != NSNotFound)) {
occurrences++;
searchRange.location = foundRange.location+foundRange.length;
searchRange.length = [string length] - (foundRange.location+foundRange.length);
}
}while (foundRange.location != NSNotFound);
return occurrences;
}