Swift:从全名字符串中拆分名字和姓氏

时间:2017-08-17 03:23:41

标签: ios swift split

如何将全名拆分为姓氏和名字。虽然我已经完成了以下代码,但有没有更好的方法来考虑fullName的下面的值?

全名可以包含以下任何值:

let fullName:String! //(No first or last name)
let fullName = "" //(No first or last name)
let fullName = "Micky" //(fName = Micky, no lName)
let fullName = "Micky Arthur" //(fName = Micky, lName = Arther)
let fullName = "Micky Arthur Test" //(fName = Micky, lName = Arther Test)

我的代码:

if let fullName = name{
   let nameParts = fullName(separatedBy: " ")
   if nameParts.count > 0{
      let fName = nameParts[0]
      var lName = ""
      if nameParts.count > 1{
          for i in 1 ..< nameParts.count{
          lName = lName + nameParts[i] + " "
      }
   }
   print("First Name: \(fName) Last Name: \(lName)")
}

5 个答案:

答案 0 :(得分:14)

尝试使用此代码

    let fullName = "testing abducio medina"
    var components = fullName.components(separatedBy: " ")
    if(components.count > 0)
    {
     let firstName = components.removeFirst()
     let lastName = components.joined(separator: " ")
     debugPrint(firstName)
     debugPrint(lastName)
    } 

答案 1 :(得分:2)

怎么样:

struct Name {
    let first: String
    let last: String

    init(first: String, last: String) {
        self.first = first
        self.last = last
    }
}

extension Name {
    init(fullName: String) {
        var names = fullName.components(separatedBy: " ")
        let first = names.removeFirst()
        let last = names.joined(separator: " ")
        self.init(first: first, last: last)
    }
}

extension Name: CustomStringConvertible {
    var description: String { return "\(first) \(last)" }
}

用法(例如游乐场)

func testName(fullName: String) {
    let name = Name(fullName: fullName)
    print(name.first)
    print(name.last)
    print(name)
}

testName(fullName: "Jane Doe Foo")
//prints
// Jane
// Doe Foo
// Jane Doe Foe


testName(fullName: "John Doe")
//prints
// John
// Doe
// Jane Doe

答案 2 :(得分:0)

我做过像这样的事情

var Name = "first name"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
let middlename: String = fullNameArr.indices.contains(2)? fullNameArr[1] : ""
if fullNameArr.count > 1 {
     var lastName: String? = fullNameArr.last

}

答案 3 :(得分:0)

试试这个:

let scoreToken = tokenScore group
   log group.Proportion +
   (document |> Seq.sumBy scoreToken)

答案 4 :(得分:0)

简单的解决方案和更少的行:

let firstName = name.components(separatedBy: "")[0]
let secondName = name.components(separatedBy: "")[1]