swift - String:缩短第一个单词

时间:2015-04-13 05:58:23

标签: swift

我有字符串,我想缩短第一个单词并使其像这样; 有没有办法呢?

var name = "John Doe" ---> “J. Doe”

谢谢,

6 个答案:

答案 0 :(得分:3)

尝试这样的事情,拆分空间然后抓住第一个数组的第一个字符。这是一个巧妙的技巧,因为字符串是一个字符数组。

var name = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var shortName = "\(fullNameArr[0][0]). \(fullNameArr[1])"

答案 1 :(得分:3)

您可以使用componentsByString方法的组件。

extension String {
    var shortName: String {
        let components = componentsSeparatedByString(" ").map{$0.capitalizedString}
        return String(components.first![startIndex]) + ". " + components.last!
    }
}
println("John Doe".shortName)    // "J. Doe"
println("leonardo savio dabus".shortName)    // "L. Dabus"

或作为一种功能:

func shortName(fullName: String) -> String {
    let components = fullName.componentsSeparatedByString(" ").map{$0.capitalizedString}
    return String(components.first![fullName.startIndex]) + ". " + components.last!
}

let short = shortName("John Doe")   // "J. Doe"

答案 2 :(得分:1)

以下是您的简单功能:

var name = "John Doe"
func updateName(name: String) -> String {

    let firstName: String = name.componentsSeparatedByString(" ").first!.uppercaseString as String
    let secondName: String = name.componentsSeparatedByString(" ")[1].uppercaseString as String
    let firstLetter = firstName.startIndex
    let finalLetter = firstName[firstLetter]

    return "\(finalLetter). \(secondName)"
}

updateName(name)  // "J. doe"

答案 3 :(得分:1)

谢谢大家,凭借我有限的编程经验,我结合了你们所有人给我的东西;

let name = authorname
let wordsArray = name.componentsSeparatedByString(" ")
var firstWord = wordsArray[0]
var secondWord = wordsArray[1]
var firstChar = Array(firstWord)[0]
var shortName = "\(firstChar). \(secondWord)"
self.title = shortName

答案 4 :(得分:0)

处理中,双中,昵称等。

var name = "John Aby Doe"
var fullNameArr = split(name) {$0 == " "}
if let first = fullNameArr.first {
    var shortName = "\(first[first.startIndex])."
    for part in fullNameArr {
        if part != first {
            shortName += " \(part)"
        }
    }
    println(shortName)
}

答案 5 :(得分:0)

这可以是替代方法。感谢

  var name = "John Doe"
     var FirstPart : String = name.componentsSeparatedByString(" ")[0] as String
        var secondPart : String = name.componentsSeparatedByString(" ")[1] as String
        var firstLetter = FirstPart[FirstPart.startIndex]
        var shortName = "\(firstLetter). \(secondPart)"
print(shortName) // prints J. Doe