查找字符串上 NSArray 对象的数量

发布于 2024-11-17 08:29:25 字数 159 浏览 1 评论 0原文

我想计算我的 NSString 的 NSArray 对象。我的 NSArray 有 @"a"@"w" 对象,我的字符串是 @"abcdefgw"。我想知道 @"w" 对象在我的字符串中出现了多少次。

I would like to count my NSArray object of my NSString. My NSArray has @"a", @"w" objects, and my string is @"abcdefgw". I would like to know how many times the @"w" object is there in my string.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

べ映画 2024-11-24 08:29:25

您可以使用 - (NSArray *)componentsSeparatedByString:(NSString *)separator,尽管这可能存在边界问题。您还可以像这样使用 stringByReplacingOccurrencesOfString:withString: :

NSString *shortString = [myString stringByReplacingOccurrencesOfString:@"w" withString:@""];
return mystring.length-shortString.length;

You can use - (NSArray *)componentsSeparatedByString:(NSString *)separator, though this may have boundary issues. You can also use stringByReplacingOccurrencesOfString:withString: like this:

NSString *shortString = [myString stringByReplacingOccurrencesOfString:@"w" withString:@""];
return mystring.length-shortString.length;
与酒说心事 2024-11-24 08:29:25

如果你想计算子字符串,你将不得不搜索子字符串,然后每次缩小范围......类似的东西。

-(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;
}

if you are looking to count substrings you will have to search for substrings then shrink the range each time... something like.

-(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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文