Swift:将一个字符串拆分成一个数组
说我在这里有一个字符串:
var fullName: String = "First Last"
我想在空白处分割字符串,并将值分配给它们各自的变量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
另外,有时用户可能没有姓氏。
Swift的方法是使用全局split
函数,如下所示:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
与斯威夫特2
在Swift 2中,由于引入了内部CharacterView类型,分割的使用变得更复杂一些。 这意味着String不再采用SequenceType或CollectionType协议,而必须使用.characters
属性来访问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
只需在你的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]
最简单的方法是使用componentsSeparatedBy:
对于Swift 2:
import Foundation
let fullName : String = "First Last";
let fullNameArr : [String] = fullName.componentsSeparatedByString(" ")
// And then to access the individual words:
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
对于Swift 3:
import Foundation
let fullName : String = "First Last"
let fullNameArr : [String] = fullName.components(separatedBy: " ")
// And then to access the individual words:
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
链接地址: http://www.djcxy.com/p/56491.html