假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
当前回答
这是用于swift 4.2在20181206 1610的字符串和CSV文件
var dataArray : [[String]] = []
let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
let url = URL(fileURLWithPath: path!)
do {
let data = try Data(contentsOf: url)
let content = String(data: data, encoding: .utf8)
let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
for line in parsedCSV!
{
dataArray.append(line)
}
}
catch let jsonErr {
print("\n Error read CSV file: \n ", jsonErr)
}
print("\n MohNada 20181206 1610 - The final result is \(dataArray) \n ")
其他回答
这在Beta 5中再次发生了变化。哭泣!它现在是CollectionType上的一个方法
旧版本:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
新建:
var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}
苹果发行说明
斯威夫特2.2添加了错误处理和大写字符串:
func setFullName(fullName: String) {
var fullNameComponents = fullName.componentsSeparatedByString(" ")
self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""
self.fname = self.fname!.capitalizedString
self.sname = self.sname!.capitalizedString
}
将字符串拆分为数组的简单方法
var fullName:String=“First Last”;var fullNameArr=fullName.componentsSeparatedByString(“”)var firstName:String=fullNameArr[0]var lastName:String=fullNameArr[1]
let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
我有一个场景,其中多个控制字符可以出现在我要拆分的字符串中。我只是让苹果处理这一部分,而不是维护一系列这些。
以下功能适用于iOS 10上的Swift 3.0.1:
let myArray = myString.components(separatedBy: .controlCharacters)