在Swift数组中查找唯一值 [英] Find unique values in a Swift Array

查看:84
本文介绍了在Swift数组中查找唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个项目,告诉我一段文本中的唯一单词.

I am building a project that tells me the unique words in a piece of text.

我有我的原始字符串 scriptTextView ,我已将每个单词添加到数组 scriptEachWordInArray

I have my orginal string scriptTextView which I have added each word into the array scriptEachWordInArray

我现在想创建一个名为 scriptUniqueWords 的数组,该数组仅包含在 scriptEachWordInArray

I would now like to create an array called scriptUniqueWords which only includes words that appear once (in other words are unique) in scriptEachWordInArray

因此,我希望我的scriptUniqueWords数组等于= ["Silent","Holy"].

So I'd like my scriptUniqueWords array to equal = ["Silent","Holy"] as a result.

我不想创建一个没有重复项的数组,而是创建一个仅具有一次出现一次的值的数组.

var scriptTextView = "Silent Night Holy Night"
var scriptEachWordInArray = ["Silent", "night", "Holy", "night"]
var scriptUniqueWords = [String]()

for i in 0..<scriptEachWordInArray.count {

    if scriptTextView.components(separatedBy: "\(scriptEachWordInArray[i]) ").count == 1 {
        scriptUniqueWords.append(scriptEachWordInArray[i])
        print("Unique word \(scriptEachWordInArray[i])")}

}

推荐答案

您可以使用NSCountedSet

let text = "Silent Night Holy Night"
let words = text.lowercased().components(separatedBy: " ")
let countedSet = NSCountedSet(array: words)
let singleOccurrencies = countedSet.filter { countedSet.count(for: $0) == 1 }.flatMap { $0 as? String }

现在singleOccurrencies包含["holy", "silent"]

这篇关于在Swift数组中查找唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆