swift - 寻找在 Swift 中从字符串中过滤文本的最佳方法

标签 swift data-structures

我有一个按升序排列的字符串数组。我想过滤该数组中的字符/文本,并首先从搜索的文本字母中获取结果,然后再从其余的中获取结果。我正在寻找完成这项工作的最简单方法。 示例:

Var array = ["Anand", "Ani", "Dan", "Eion", "Harsh", "Jocab", "Roshan", "Stewart"]

搜索文本是“R”

输出应该是:

Var outArray = ["Roshan", "Harsh", "Stewart"]

最佳答案

实现此目的的一种方法是首先将字符串映射到一个元组,该元组包含字符串中搜索文本的索引以及字符串本身。然后按索引排序,然后将元组映射回字符串。

let array = ["Anand", "Ani", "Dan", "Eion", "Harsh", "Jocab", "Roshan", "Stewart"]
let searchText = "R"
// compactMap acts as a filter, removing the strings where string.index(of: searchText, options: [.caseInsensitive]) returns nil
let result = array.compactMap { string in string.index(of: searchText, options: [.caseInsensitive]).map { ($0, string) } }
                    .sorted { $0.0 < $1.0 }.map { $0.1 }

index(of:options:) 方法取自 this answer here .

对于 Swift 4.x:

extension StringProtocol where Index == String.Index {
    func index(of string: Self, options: String.CompareOptions = []) -> Index? {
        return range(of: string, options: options)?.lowerBound
    }
    func endIndex(of string: Self, options: String.CompareOptions = []) -> Index? {
        return range(of: string, options: options)?.upperBound
    }
    func indexes(of string: Self, options: String.CompareOptions = []) -> [Index] {
        var result: [Index] = []
        var startIndex = self.startIndex
        while startIndex < endIndex,
            let range = self[startIndex...].range(of: string, options: options) {
                result.append(range.lowerBound)
                startIndex = range.lowerBound < range.upperBound ? range.upperBound :
                    index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
        }
        return result
    }
    func ranges(of string: Self, options: String.CompareOptions = []) -> [Range<Index>] {
        var result: [Range<Index>] = []
        var startIndex = self.startIndex
        while startIndex < endIndex,
            let range = self[startIndex...].range(of: string, options: options) {
                result.append(range)
                startIndex = range.lowerBound < range.upperBound ? range.upperBound :
                    index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
        }
        return result
    }
}

关于swift - 寻找在 Swift 中从字符串中过滤文本的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785296/

相关文章:

ios - 如何在 Swift 中为 UIButton 设置 Title Padding (Inset)

swift - NSApplicationDelegate 在没有 Storyboard 的情况下无法工作

ios - 为什么 CGImage 的 copy() 方法会在相同的内存地址上生成图像?

c++ - 如何使用 `std::multimap` 或任何其他容器对多个值进行排序?

python - 访问二维列表的元素

c - 我想将数据插入二叉树,但在 3 个输入后显示段错误

swift - 解决 iOS Swift 中的数据争用

ios - 在 iOS 中获取准确位置

c++ - 并发可变优先级队列

perl - 在 Perl 中插入散列的末尾