在SWIFT中将字符串拆分成数组?假设我这里有一根绳子:var fullName: String = "First Last"我希望将字符串拆分为空格,并将值赋值给它们各自的变量。var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]var lastName: String? = fullnameArr[1]而且,有时用户可能没有姓。
3 回答
MYYA
TA贡献1868条经验 获得超4个赞
split
var fullName = "First Last"var fullNameArr = split(fullName) {$0 == " "}var firstName: String = fullNameArr[0]var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
.characters
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] // FirstfullNameArr[1] // Last
潇潇雨雨
TA贡献1833条经验 获得超4个赞
componentsSeparatedByString
fullName
import Foundationvar fullName: String = "First Last"let fullNameArr = fullName.componentsSeparatedByString(" ") var firstName: String = fullNameArr[0]var lastName: String = fullNameArr[1]
SWIFT 3+更新
import Foundationlet fullName = "First Last"let fullNameArr = fullName.components(separatedBy: " ")let name = fullNameArr[0]let surname = fullNameArr[1]
PIPIONE
TA贡献1829条经验 获得超9个赞
最简单的方法是使用组件sSeparatedBy:
SWIFT 2:
import Foundationlet 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 Foundationlet 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]
- 3 回答
- 0 关注
- 1302 浏览
添加回答
举报
0/150
提交
取消