如何检查数组中的句子是否包含Swift中的确切单词?

时间:2016-08-06 14:50:30

标签: ios arrays swift algorithm

例如,我有以下数组:

var reviews = ["Skating is good in Austria", 
"I loved the Spanish food, it had so many varieties and 
it was super super delicious. The price was a little bit high but 
it was worth it. People who don't like spicy food might need 
to think twice as it could be a little bit problematic for them.", 
"I didn’t like the Indian food!", 
"People were really friendly, I enjoyed being there."]

var words = ["Skating", "Food", "Climbing"]

现在我想检查,如果这些评论包含我的一个单词。

挑战是:一个或多个评论可以包含这些单词,我想找到这些评论,将它们添加到一个数组中并打印。

为此我做:

var arr = [String]()

for review in reviews {
    for word in words {
        if review.containsString(word) {
            arr.append(review)
        }
    }
    print(arr)
}

但只打印第一句话:

["Skating is good in Austria"]

因此,我想检查一个或多个评论是否包含数组中的这些单词,然后将所有这些匹配的评论放入arr数组中。

任何人都可以帮助我吗?我很困惑为什么只需要一次审核并在

之后停止

3 个答案:

答案 0 :(得分:3)

您需要将print句子移出循环。

像这样:

var arr = [String]()

for review in reviews {
    for word in words {
        if review.containsString(word) {
            arr.append(review)
        }
    }
}
print(arr)

此外,如果您不想获得重复评论,我会使用set代替数组:var arr = Set<String>()

此外,您可能需要不区分大小写的字符串比较。在单词数组中按Food更改food,然后重试。

要获得完整的不区分大小写的循环,请尝试以下方法:

for review in reviews {
    for word in words {
        if review.lowercaseString.containsString(word.lowercaseString) {
            arr.append(review)
        }
    }
}
print(arr)

答案 1 :(得分:1)

如果您想要使用字符串忽略大小写,只需使用filter array方法尝试这种方式,就会减少循环代码。

var predicateString = [String]()
for word in words {
    predicateString(String(format:"SELF CONTAINS[cd] %@", word)
}
let predicate = NSPredicate(format: "%@",predicateString.joined(separator: " || "));
let filteredArray = reviews.filter { predicate.evaluateWithObject($0) };
print(filteredArray)

答案 2 :(得分:1)

您可以使用功能编程

首先让我们创建一个小写关键字数组(我假设你想要不区分大小写的匹配)。

let keywords = words.map { $0.lowercaseString }

下一步

let matchingSentences = reviews.filter { sentence  in
    let lowerCaseSentence = sentence.lowercaseString
    return keywords.contains { keyword in sentence.rangeOfString(keyword) != nil }
}

结果

matchingSentences.forEach { print($0) }

Skating is good in Austria
I loved the Spanish food, it had so many varieties and it was super super delicious. The price was a little bit high but it was worth it. People who don't like spicy food might need to think twice as it could be a little bit problematic for them.
I didn’t like the Indian food!

较短版本

let res = reviews.filter { sentence in keywords.contains { sentence.lowercaseString.rangeOfString($0) != nil } }