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

var fullName: String = "First Last"

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

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

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

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


当前回答

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

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)

其他回答

Swift 4、Xcode 10和iOS 12更新100%工作

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullNameArr[1] //Last

有关更多信息,请参阅此处的Apple文档。

var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last =  fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"

不允许使用相同的名字和姓氏如果全名无效,则取占位符值“John Doe”

大多数这些答案都假设输入包含一个空格,而不是空白,并且只有一个空格。如果你能安全地做出这样的假设,那么(来自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"]

根据Swift 2.2

您只需编写2行代码,就会得到拆分字符串。

let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1]) 

享受。:)

只有拆分才是正确的答案,这里有两个以上空格的差异。

雨燕5

var temp = "Hello world     ni hao"
let arr  = temp.components(separatedBy: .whitespacesAndNewlines)
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr2 = temp.components(separatedBy: " ")
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr3 = temp.split(whereSeparator: {$0 == " "})
// ["Hello", "world", "ni", "hao"]