假设我这里有一个字符串:

var fullName: String = "First Last"

我想在空白处拆分字符串,并将值分配给它们各自的变量

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

此外,有时用户可能没有姓氏。


当前回答

将字符串拆分为数组的简单方法

var fullName:String=“First Last”;var fullNameArr=fullName.componentsSeparatedByString(“”)var firstName:String=fullNameArr[0]var lastName:String=fullNameArr[1]

其他回答

斯威夫特4

let words = "these words will be elements in an array".components(separatedBy: " ")

Swift 5.2的更新和最简单的方式

let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])

这张照片,

[“Bob”,“hit”,“a”,“ball”,“the”,“击球”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,“Hie”,“How”,“u”,“”]

但是,如果要过滤空字符串,

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})

输出

[“Bob”,“hit”,“a”,“ball”,“the”,“命中”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,”Hie“,”How“,”r“,”u“]

但请确保,Foundation已导入。

您可以使用此公共函数并添加任何要分隔的字符串

func separateByString(String wholeString: String, byChar char:String) -> [String] {

    let resultArray = wholeString.components(separatedBy: char)
    return resultArray
}

var fullName: String = "First Last"
let array = separateByString(String: fullName, byChar: " ")
var firstName: String = array[0]
var lastName: String = array[1]
print(firstName)
print(lastName)

斯威夫特2.2添加了错误处理和大写字符串:

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}

这直接提供了一个分割部分的数组

var fullNameArr = fullName.components(separatedBy:" ")

那么你可以这样使用,

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]