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

var fullName: String = "First Last"

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

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

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

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


当前回答

Xcode 8.0/Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

漫长的道路:

var fullName: String = "First Last"
fullName += " " // this will help to see the last word

var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array

for Character in fullName.characters {
    if Character == " " {
        fullNameArr.append(newElement)
        newElement = ""
    } else {
        newElement += "\(Character)"
    }
}


var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last

其他回答

雨燕3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}

返回三个字符串AAA、BBB和CCC筛选出空字段处理多个空格和制表字符如果要处理新行,请将.whittespaces替换为.whittespace和新行

斯威夫特4

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

大多数这些答案都假设输入包含一个空格,而不是空白,并且只有一个空格。如果你能安全地做出这样的假设,那么(来自bennett的)公认的答案是相当优雅的,也是我在可能的时候会采用的方法。

当我们无法做出这一假设时,一个更稳健的解决方案需要涵盖以下大多数答案没有考虑的情况:

制表符/换行符/空格(空白),包括重复出现的字符前导/尾随空格Apple/Linux(\n)和Windows(\r\n)换行符

为了涵盖这些情况,此解决方案使用正则表达式将所有空格(包括重复出现的字符和Windows换行符)转换为单个空格,然后修剪,然后拆分为单个空格:

斯威夫特3:

let searchInput = "  First \r\n \n \t\t\tMiddle    Last "
let searchTerms = searchInput 
    .replacingOccurrences(
        of: "\\s+",
        with: " ",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy: " ")

// searchTerms == ["First", "Middle", "Last"]

Xcode 8.0/Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

漫长的道路:

var fullName: String = "First Last"
fullName += " " // this will help to see the last word

var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array

for Character in fullName.characters {
    if Character == " " {
        fullNameArr.append(newElement)
        newElement = ""
    } else {
        newElement += "\(Character)"
    }
}


var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last

斯威夫特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
}