【问题标题】:Checking whether elements of an Array contains a specified String检查 Array 的元素是否包含指定的 String
【发布时间】:2017-01-08 10:40:13
【问题描述】:

我正在开发一个 iOS 应用程序。我有一个数组,

NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for(int k=0; k<qwer.count; k++) {
    //
}

我正在尝试检查我的数组是否包含字符串“wassail”。谁能帮我找到这个?

【问题讨论】:

    标签: ios objective-c nsarray


    【解决方案1】:

    NSString 有一个rangeOfString 函数,可用于查找部分字符串匹配。此函数返回NSRange。您可以使用location 属性。

    ...
      NSArray *qwer = [NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
        for (NSString *name in qwer){
          if ([name rangeOfString:keyword].location == NSNotFound) {
            NSLog(@"contains");
          } 
        }
    ...
    

    参考:

    1. https://developer.apple.com/reference/foundation/nsstring/1416849-rangeofstring
    2. https://developer.apple.com/reference/foundation/nsrange

    谢谢 斯里拉姆

    【讨论】:

      【解决方案2】:

      试试这个

      NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail",nil];
      for(int k=0; k<qwer.count; k++) {
          NSString *currentString =[qwer objectAtIndex:k];
          if ([currentString rangeOfString:@"wassail"].location == NSNotFound) {
              NSLog(@"string does not contain wassail");
          } else {
              NSLog(@"string contains wassail!");
      
              break;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-03
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 2021-03-17
        • 2017-08-08
        • 2021-04-26
        • 1970-01-01
        • 2022-09-23
        相关资源
        最近更新 更多