【问题标题】:Search through NSArray for string通过 NSArray 搜索字符串
【发布时间】:2010-12-23 15:39:53
【问题描述】:

我想在我的 NSArray 中搜索某个字符串。

例子:

NSArray 包含对象:“dog”、“cat”、“fat dog”、“thing”、“another thing”、“heck here's another thing”

我想搜索单词“another”并将结果放入一个数组中,并将另一个非结果放入另一个可以进一步过滤的数组中。

【问题讨论】:

    标签: search nsstring nsarray


    【解决方案1】:

    如果已知数组中的字符串是不同的,则可以使用集合。 NSSet 在大输入上比 NSArray 更快:

    NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];
    
    NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
    [matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];
    
    NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
    [notmatches  minusSet:matches];
    

    【讨论】:

      【解决方案2】:

      未经测试,因此可能存在语法错误,但您会明白的。

      NSArray* inputArray = [NSArray arrayWithObjects:@"dog", @"cat", @"fat dog", @"thing", @"another thing", @"heck here's another thing", nil];
      
      NSMutableArray* containsAnother = [NSMutableArray array];
      NSMutableArray* doesntContainAnother = [NSMutableArray array];
      
      for (NSString* item in inputArray)
      {
        if ([item rangeOfString:@"another"].location != NSNotFound)
          [containsAnother addObject:item];
        else
          [doesntContainAnother addObject:item];
      }
      

      【讨论】:

      • 这段代码很好用,但是我怎么能找到找到的字符串数组中的索引呢?
      • 自己解决:for (NSString* item in inputArray) { index++; if ([item rangeOfString:@"another"].location != NSNotFound) { [containsAnother addObject:item];保存索引 = 索引 - 1; } 其他 [doesntContainAnother addObject:item]; }
      【解决方案3】:

      它不起作用,因为根据文档“indexOfObjectIdenticalTo:”返回与您传入的对象具有相同内存地址的第一个对象的索引。

      你需要遍历你的数组并进行比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-08
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多