用多余的单词将字符串数组中的所有元素连接起来

时间:2018-09-22 14:06:14

标签: arrays swift string

我有一个这样的字符串数组

let arrayOfString = ["Nancy", "Peter", "Kevin"]

并且我想将所有数组元素以及逗号和空格分隔在一起。

let joinResult = arrayOfString.joined(separator: ", ")

这给了我

Nancy, Peter, Kevin

我的问题是,如果array.count> 2,是否可以在最后一个元素之前添加单词“ and”。在这种情况下,应该是

Nancy, Peter, and Kevin
//if arrayOfString = ["Nancy"], only shows Nancy with no comma and space

谢谢!

2 个答案:

答案 0 :(得分:0)

这是一个解决方案

let arrayOfString = ["Nancy", "Peter", "Kevin"]

let joinedString = arrayOfString.dropLast().joined(separator: ", ")
                   + (arrayOfString.count > 1 ? " and " : "")
                   + (arrayOfString.last ?? "")

print(joinedString)   //Nancy, Peter and Kevin

您也可以将以上内容定义为函数

func joinedNames(from array: [String]) -> String {
    return array.dropLast().joined(separator: ", ")
           + (array.count > 1 ? " and " : "")
           + (array.last ?? "")
}

并进行如下测试:

joinedNames(from: ["Nancy", "Peter", "Kevin"])  //"Nancy, Peter and Kevin"
joinedNames(from: ["Nancy", "Peter"])           //"Nancy and Peter"
joinedNames(from: ["Nancy"])                    //"Nancy"
joinedNames(from: [])                           //""

如果需要牛津逗号,请使用以下解决方案:

func joinedNamesWithOxfordComma(from array: [String]) -> String {
    return array
        .enumerated()
        .map {(index, element) in
            if index == 0 {
                return element
            } else if index <= array.count - 2 {
                return ", " + element
            } else if array.count > 2 {
                return ", and " + element
            } else {
                return " and " + element
            }
        }.joined()
}

joinedNamesWithOxfordComma(from: ["Nancy", "Peter", "Kevin"])  //"Nancy, Peter, and Kevin"
joinedNamesWithOxfordComma(from: ["Nancy", "Peter"])           //"Nancy and Peter"
joinedNamesWithOxfordComma(from: ["Nancy"])                    //"Nancy"
joinedNamesWithOxfordComma(from: [])                           //""

答案 1 :(得分:0)

这是一种安全的方法

let names = ["Nancy", "Peter", "Kevin"]

func join(names: [String], separator: String, lastSeparator: String) -> String? {
    guard !names.isEmpty else { return nil }
    guard names.count > 1 else { return names.first }
    return names
        .dropLast()
        .joined(separator: separator) + " " + lastSeparator  + " " + names.last!
}

join(names: names, separator: ",", lastSeparator: "and")

结果

"Nancy,Peter and Kevin"