如何根据字符串在元素中出现的实例数对字符串数组进行排序?

时间:2017-08-20 00:25:59

标签: swift swift3

如何根据字符串在元素中出现的实例数对字符串数组进行排序?例如:

let str = "o"
let arrayOfStrings = ["Hot", "Only open on tuesdays", "People of earth"]

//Sort here

//arrayOfString becomes ["Only open on tuesdays", "People of earth", "Hot"]

2 个答案:

答案 0 :(得分:3)

import Foundation
let str = "o"
var arrayOfStrings = ["Hot", "Only open on tuesdays", "People of earth"]

arrayOfStrings.sort {
  return $0.components(separatedBy: str).count < $1.components(separatedBy: str).count
}

print(arrayOfStrings)
// ["Hot", "Only open on tuesdays", "People of earth"]

请注意,如果我最后排序最高实例,这是正确的顺序。我从最少到大多数情况都向你展示:字符串&#34; o&#34;和字符串&#34; O&#34;是两个不同的字符串,因此原始Array中的计数为1,2,2。如果要比较不区分大小写的字符串,则必须对比较应用大写或小写操作。

以下是大多数字符串实例的结果,使用不区分大小写的比较:

arrayOfStrings.sort {
  let upper = str.uppercased()
  return $0.uppercased().components(separatedBy: upper).count >
    $1.uppercased().components(separatedBy: upper).count
}

print(arrayOfStrings)
// ["Only open on tuesdays", "People of earth", "Hot"]

答案 1 :(得分:2)

首先定义一个计算出现次数的函数 字符串中的子字符串,包括重叠事件:

extension String {
    /// Compute number of occurrences of a substring, including overlapping occurrences.
    ///
    /// - Parameters:
    ///   - substring: The substring to search for
    ///   - options: String compare options, e.g. `.caseInsensitive` (optional)
    /// - Returns: The number of occurrences of `substring` in `self`
    func count(of substring: String, options: CompareOptions = []) -> Int {
        var count = 0
        var pos = startIndex
        // Find next occurrence of `substring`:
        while let r = range(of: substring, options: options, range: pos..<endIndex) {
            count += 1
            // Continue search at the next character position:
            pos = index(after: r.lowerBound)
        }
        return count
    }
}

示例:

"Only open on tuesdays".count(of: "o", options: .caseInsensitive) == 3
"aooob".count(of: "oo") == 2

这可用于根据数字对字符串数组进行排序 子串的出现(内联说明):

let str = "o"
let arrayOfStrings = ["Hot", "Only open on tuesdays", "People of earth"]

// Compute number of occurrences of `str` for each array element:
let counts = arrayOfStrings.map { $0.count(of: str, options: .caseInsensitive) }
print(counts) // [1, 3, 2]

// Sort array indices according to number of occurences of `str` in array element (decreasing):
let sortedIndices = arrayOfStrings.indices.sorted(by: { counts[$0] > counts[$1] })
print(sortedIndices) // [1, 2, 0]

// Create new array from sorted array indices:
let sortedArray = sortedIndices.map { arrayOfStrings[$0] }
print(sortedArray) // ["Only open on tuesdays", "People of earth", "Hot"]