Objective-C 在 NSArray 中搜索字符串?

发布于 2024-09-16 11:13:54 字数 44 浏览 2 评论 0原文

我有一个字符串数组。

我如何才能找出字符串在数组中的索引?

I have an array of strings.

How might I be able to figure out what index a string is in a array?

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

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

发布评论

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

评论(2

爱要勇敢去追 2024-09-23 11:13:54

虽然很老了,但这个问题在谷歌搜索中的排名很高。这是使用块的版本,

- (void)testSearch
{
    NSArray *hashAlgorithms = @[@"SHA1", @"SHA2", @"SHA256", @"SHA384", @"SHA512"];
    NSString *searchFor = @"SHA384";
    __block NSInteger index = NSNotFound;
    [hashAlgorithms enumerateObjectsUsingBlock:^(id alg, NSUInteger idx, BOOL *stop) {
        if ([alg compare:searchFor options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSLog(@"Found: %@", searchFor);
            *stop = YES;
            index = idx;
        } else {
            NSLog(@"NOT Equal: %@", alg);
        }
    }];

    if (index == NSNotFound) {
        NSLog(@"Not found. %li", (long)index);
    } else {
        NSLog(@"Found at: %li", (long)index);
    }
}

Though very old but this question comes quite high in google search. Here is a version in using block,

- (void)testSearch
{
    NSArray *hashAlgorithms = @[@"SHA1", @"SHA2", @"SHA256", @"SHA384", @"SHA512"];
    NSString *searchFor = @"SHA384";
    __block NSInteger index = NSNotFound;
    [hashAlgorithms enumerateObjectsUsingBlock:^(id alg, NSUInteger idx, BOOL *stop) {
        if ([alg compare:searchFor options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSLog(@"Found: %@", searchFor);
            *stop = YES;
            index = idx;
        } else {
            NSLog(@"NOT Equal: %@", alg);
        }
    }];

    if (index == NSNotFound) {
        NSLog(@"Not found. %li", (long)index);
    } else {
        NSLog(@"Found at: %li", (long)index);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文