从名称中获取首字母并将其限制为2个首字母 [英] Get the initials from a name and limit it to 2 initials

查看:126
本文介绍了从名称中获取首字母并将其限制为2个首字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下名字: John Fitzgerald Kennedy

为了得到它的首字母,我创建了一个方法:

To get its initials, I created a method:

extension String {
    public var first: String {
        return String(self[startIndex])
    }
}

let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
      .reduce("") { $0 + $1.first }

输出为: JFK

我的方法(使用reduce)是否有一种优雅的方式将这些首字母限制为 JK ,然后删除字母中间?

Is there an elegant way with my method (with reduce) to limit those initials to JK only, removing then the letter in the middle?

推荐答案

Swift 2.0

这个怎么样:

let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.reduce("") { ($0 == "" ? "" : $0.first) + $1.first}

这也将照顾名称没有中间的情况名称或多于1个中间名。

That will also take care of the case where the name has no middle name or more than 1 middle name.

Swift 3

let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.characters.first!)") + "\($1.characters.first!)" }

Swift 4

let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }

这篇关于从名称中获取首字母并将其限制为2个首字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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