【问题标题】:Converting an array of strings to an array of concatenated strings将字符串数组转换为串联字符串数组
【发布时间】:2018-03-08 03:28:20
【问题描述】:

我正在寻找一种通用且实用的解决方案,将数组的 x 元素连接到新的字符串数组。从第一个元素开始,第一个到第二个,第二个到第三个等等......抱歉解释不是很清楚,但我很难说出我想要实现的目标。所以我会尝试用例子来演示。

1) 如果我想将字母 2 与 2 连接起来,我会使用这个函数:

    var letters = ["a","b","c","d","e"]

   func concatenateStrings(array: [String]) -> [String] {
        return array.reduce([], { (result: [String], item:String) -> [String] in
            guard !result.isEmpty else {
                return [item] //first item
            }

            return result + [ array[result.count - 1] + " \(item)"]
        })
    }

这会产生这个结果["a", "a b", "b c", "c d", "d e"]

2) 3 乘 3

  func concatenateStrings(array: [String]) -> [String] {
        return array.reduce([], { (result: [String], item:String) -> [String] in
            guard !result.isEmpty else {
                return [item] //first item
            }
            guard result.count != 1 else {
                return result + [array[result.count - 1] + " \(item)"] // second item
            }
            let first = array[result.count - 2]
            let second = array[result.count - 1]
            return result + [ "\(first) " + second + " \(item)"]
        })
    }

这给了我["a", "a b", "a b c", "b c d", "c d e"]

我的问题是如何推广这种方法,例如,如果我想通过连接 4 个元素、5 个数组元素等来生成一个新的字符串数组......

谢谢,如果还有什么不清楚的地方,我会很乐意尝试更彻底。

【问题讨论】:

    标签: ios arrays swift swift3


    【解决方案1】:

    一个可能的解决方案(Swift 3+4):

    func concatenateStrings(array: [String], maxLength: Int) -> [String] {
    
        let nestedArray = array.reduce([[String]]()) { (result, item) -> [[String]] in
            let last = result.last ?? []
            return result + [Array((last + [item]).suffix(maxLength))]
        }
        return nestedArray.map { $0.joined(separator: " ") }
    }
    

    例子:

    let letters = ["a","b","c","d","e"]
    print(concatenateStrings(array: letters, maxLength: 3))
    // ["a", "a b", "a b c", "b c d", "c d e"]
    

    函数首先创建一个嵌套的字符串数组,例如

    [["a"], ["a", "b"], ["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"]]
    

    通过将当前项目附加到最后一个元素,并使用 suffix() 限制长度。然后将内部数组连接起来。

    在 Swift 4 中,您还可以使用 reduce(into:),它创建的更少 中间数组,见SE-0171 Reduce with inout:

    func concatenateStrings(array: [String], maxLength: Int) -> [String] {
    
        let nestedArray = array.reduce(into: [[String]]()) { (result, item) in
            let last = result.last ?? []
            result.append(Array((last + [item]).suffix(maxLength)))
        }
        return nestedArray.map { $0.joined(separator: " ") }
    }
    

    【讨论】:

    • 你也可以将 maxLength 设为可选 func concatenateStrings(array: [String], maxLength: Int? = nil) -> [String] { let maxLength = maxLength ?? array.count
    • 惊人的解决方案马丁。正是我需要的。谢谢!
    • @LeoDabus:当然。也可以使分隔符成为参数。出于演示目的,我会保持简单。
    • @MartinR btw 很好的增加了 reduce 方法能够改变 Swift 4 中的结果
    • @LeoDabus:是的,这是 Swift 4 中一个有用的补充。
    【解决方案2】:

    给定青年输入数组

    let elms = ["a","b","c","d","e"]
    

    这里有一个迭代函数来实现你所需要的

    Swift 4 版本

    func concatenations(elms:[String], maxLength: Int) -> [String] {
    
        var result:[String] = []
    
        var word = ""
    
        for elm in elms {
            if word.count >= maxLength {
                word.removeFirst()
                word.append(elm)
            } else {
                word.append(elm)
            }
            result.append(word)
        }
        return result
    }
    

    示例

    concatenations(elms: elms, maxLenght: 2)
    // ["a", "ab", "bc", "cd", "de"]
    
    
    concatenations(elms: elms, maxLenght: 3)
    // ["a", "ab", "abc", "bcd", "cde"]
    
    
    concatenations(elms: elms, maxLenght: 4)
    // ["a", "ab", "abc", "abcd", "bcde"]
    

    【讨论】:

    • 你可以只使用收集方法 dropFirst 而不是word.remove(at: word.startIndex)
    • @LeoDabus 这绝对更好。我更新了我的代码。谢谢你的建议。
    • 您也可以将 maxLenght 参数设为可选 Int func concatenations(elms:[String], maxLenght: Int? = nil) 并在您的方法中添加 let maxLenght = maxLenght ?? elms.count。顺便说一句,OP希望字符用空格分隔
    • @LeoDabus 实际上我认为maxLength 是明确需要解决OP 描述的问题。
    猜你喜欢
    • 2017-11-27
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多