将字符串数组转换为连接字符串数组。

时间:2021-05-26 21:14:14

Im looking for a general and functional solution to concatenate x elements of an array to a new array of strings. Beginning from the first element, first with second, second with third and so on ... Sorry for the explanation not being very clear, but it has been hard for me to put on name on what I'm trying to achieve. So I will try to demonstrate it with examples.

我正在寻找一种通用的和功能的解决方案,将数组的x元素连接到一个新的字符串数组中。从第一个元素开始,第一个元素,第二个元素,第三个元素等等……很抱歉我的解释不太清楚,但是我很难说出我想要达到的目标。我会用例子来说明。

1) If I'm trying to concatenate the letters 2 by 2 I'm using this function:

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)"]
        })
    }

which produces me this result ["a", "a b", "b c", "c d", "d e"]

这就产生了这个结果[a, a b, b c, c d, d e]

2) 3 by 3

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)"]
        })
    }

which gives me ["a", "a b", "a b c", "b c d", "c d e"]

这就得到了[a, a b, a b c, b c d, c d e]

My question is how can I generalize this method, if for example I want to produce a new array of strings by concatenating 4 elements, 5 elements of array and so on...

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

Thank you, and if there is still something unclear I will happily try to be more thorough.

谢谢你,如果还有什么不清楚的地方,我会很高兴地尽量讲得更透彻。

2 个解决方案

#1


4  

A possible solution (Swift 3+4):

一种可能的解决方案(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: " ") }
}

Example:

例子:

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"]

The function first creates a nested array of strings, for example

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

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

by appending the current item to the last element, and using suffix() to limit the length. Then the inner arrays are concatenated.

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

In Swift 4 you can also use reduce(into:) which creates less intermediate arrays, see SE-0171 Reduce with inout:

在Swift 4中,您还可以使用reduce(into:)来创建更少的中间数组,见SE-0171 reduce和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: " ") }
}

#2


1  

Given youth input array

鉴于青年输入数组

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

Here's an iterative function to achieve what you need

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

Swift 4 version

斯威夫特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
}

Examples

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"]

#1


4  

A possible solution (Swift 3+4):

一种可能的解决方案(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: " ") }
}

Example:

例子:

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"]

The function first creates a nested array of strings, for example

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

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

by appending the current item to the last element, and using suffix() to limit the length. Then the inner arrays are concatenated.

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

In Swift 4 you can also use reduce(into:) which creates less intermediate arrays, see SE-0171 Reduce with inout:

在Swift 4中,您还可以使用reduce(into:)来创建更少的中间数组,见SE-0171 reduce和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: " ") }
}

#2


1  

Given youth input array

鉴于青年输入数组

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

Here's an iterative function to achieve what you need

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

Swift 4 version

斯威夫特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
}

Examples

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"]