假设我这里有一个字符串:
var fullName: String = "First Last"
我想根据空格分割字符串并将值分配给它们各自的变量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
此外,有时用户可能没有姓氏。
只需在您的 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]
关于ios - 在 Swift 中将字符串拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41755093/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |