假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
当前回答
let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
其他回答
根据Swift 2.2
您只需编写2行代码,就会得到拆分字符串。
let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1])
享受。:)
作为WMios答案的替代方案,您还可以使用componentsSeparatedByCharactersSet,这在分隔符(空格、逗号等)较多的情况下非常方便。
使用您的特定输入:
let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["First", "Last"]
使用多个分隔符:
let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["Last", "First", "Middle"]
在Swift 4中将字符串拆分为数组的步骤。
赋值字符串基于@spling。
注意:variableName.components(separatedBy:“split关键字”)
let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."
let fullNameArr = fullName.components(separatedBy: "@")
print("split", fullNameArr)
雨燕3
let line = "AAA BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
返回三个字符串AAA、BBB和CCC筛选出空字段处理多个空格和制表字符如果要处理新行,请将.whittespaces替换为.whittespace和新行
Swift 5.2的更新和最简单的方式
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
这张照片,
[“Bob”,“hit”,“a”,“ball”,“the”,“击球”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,“Hie”,“How”,“u”,“”]
但是,如果要过滤空字符串,
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})
输出
[“Bob”,“hit”,“a”,“ball”,“the”,“命中”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,”Hie“,”How“,”r“,”u“]
但请确保,Foundation已导入。