假设我这里有一个字符串:
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 = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
此外,有时用户可能没有姓氏。
当前回答
斯威夫特4
let string = "loremipsum.dolorsant.amet:"
let result = string.components(separatedBy: ".")
print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")
输出
loremipsum
dolorsant
amet:
total: 3
其他回答
这在Beta 5中再次发生了变化。哭泣!它现在是CollectionType上的一个方法
旧版本:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
新建:
var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}
苹果发行说明
Swift的方法是使用全局拆分函数,如下所示:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
使用Swift 2
在Swift 2中,由于引入了内部CharacterView类型,拆分的使用变得有点复杂。这意味着String不再采用SequenceType或CollectionType协议,您必须改为使用.characts属性来访问String实例的CharacterView类型表示。(注意:CharacterView确实采用SequenceType和CollectionType协议)。
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
您可以使用此公共函数并添加任何要分隔的字符串
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 Dev.4.0(2017年5月24日)
Swift 4(Beta版)中拆分了一个新功能。
import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)
输出:
["Hello", "Swift", "4", "2017"]
访问值:
print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017
Xcode 8.1/Swift 3.0.1
这是多个分隔符与数组的方式。
import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)
输出:
["12", "37", "2", "5"]
只需在fullName上调用componentsSeparatedByString方法
import Foundation
var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")
var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
Swift 3更新+
import Foundation
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]
let surname = fullNameArr[1]