用不同的最终定界符连接字符串数组 [英] Join an array of strings with a different final delimiter

查看:101
本文介绍了用不同的最终定界符连接字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常:我如何加入一个字符串数组,以使最后一个定界符与其他定界符不同?

Generally: How do I join an array of stings such that the last delimiter is different than the others?

具体来说:iOS Messages应用如何构造默认值群组对话的名称,它是联系人名称的列表?

Specifically: How does the iOS Messages app construct the default name of a group conversation, which is a list of contacts' names?

示例

class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

let users = [
    User(name: "Matthew"),
    User(name: "Mark"),
    User(name: "Luke"),
    User(name: "John")
]

users.list(" & ") { $0.name } // => "Matthew, Mark, Luke & John"

PHP

  • Implode array with ", " and add "and " before last item
  • Replace the last comma with an & sign
  • How to edit the implode so it will join values with two strings?

Ruby(在Rails上)

Ruby (on Rails)

  • Rails join a list of strings with commas and "and" before the last

Python

  • How to join list in Python but make the last separator different?

C#(Linq)

  • Comma separated list with "and" in place of the last comma

推荐答案

使用问题中定义的类您可以执行以下操作:

Using the class defined in the question you could do something like this:

let names = users.map { $0.name }
let suffix = names.suffix(2)
let joined = (names.dropLast(suffix.count) + [suffix.joinWithSeparator(" & ")]).joinWithSeparator(", ")

print(joined)   // prints Matthew, Mark, Luke & John

这篇关于用不同的最终定界符连接字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆