gpt4 book ai didi

ios - NSPredicate 在 Objective C 中查找多个单词

转载 作者:行者123 更新时间:2023-11-28 18:28:08 24 4
gpt4 key购买 nike

我有这段代码可以在字符串中搜索特定的单词,例如 Canada Poland México示例:

  NSString *valueOfUser = @"I want Poland"

NSPredicate *pred =[NSPredicate predicateWithFormat: @"SELF contains[c] %@", valueOfUser];

NSArray *arr = @[
@"Canada",
@"Poland",
@"México"
];

NSArray *filtered = [arr filteredArrayUsingPredicate: pred];
// But this array always contain 0 elements

我的错误在哪里?

我想找到这样的解决方案:

NSString *valueOfUser = @"I want Poland"
filtered[0] -> "Poland"

NSString *valueOfUser = @"I choose Poland and México"
filtered[0] -> "Poland"
filtered[1] -> "México"

最佳答案

你的查询应该是相反的:valueOfUser CONTAINS[c] SELF,试试这个:

Objective-C :

NSString *valueOfUser = @"I want Poland";

NSPredicate *pred =[NSPredicate predicateWithFormat: @"%@ contains[c] SELF", valueOfUser];

NSArray *arr = @[
@"Canada",
@"Poland",
@"México"
];

NSArray *filtered = [arr filteredArrayUsingPredicate: pred];

swift :

        let dataSource = ["Canada","Poland","México"] as NSArray
let searchString = "I choose Poland and México"
let predicate = NSPredicate(format: "%@ contains[c] SELF", searchString)
let dataArray = dataSource.filter { predicate.evaluate(with: $0) }

关于ios - NSPredicate 在 Objective C 中查找多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47008080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com