Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Split first name and last name from full name string

Tags:

split

ios

swift

How to split full name into first and last name. Though I have done following code, is there any better way considering the below values of fullName?

Full name can have any of these values:

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)

My Code:

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)")
}
like image 514
Chanchal Raj Avatar asked Aug 17 '17 03:08

Chanchal Raj


People also ask

How do you split a string into two parts in Swift?

Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.

How do you split a string after a specific character in Swift?

To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.

How do you split a word in Swift?

To split a string to an array in Swift by a character, use the String. split(separator:) function. However, this requires that the separator is a singular character, not a string.


1 Answers

 func splitContactFullName(name: String?) -> (firstName: String?, lastName: String?) {
    let namePieces = name?.components(separatedBy: " ")
    let firstName = namePieces?[0]
    var lastName = ""
    if (namePieces?.count ?? 0) > 1 {
        lastName = namePieces?[1] ?? ""
        for i in 2..<(namePieces?.count ?? 0) {
            lastName += " \(namePieces?[i] ?? "")"
        }
    }
    return (firstName, lastName)
}
like image 105
Stone Monk Avatar answered Sep 23 '22 22:09

Stone Monk