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)")
}
Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With