假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
当前回答
斯威夫特4
let string = "loremipsum.dolorsant.amet:"
let result = string.components(separatedBy: ".")
print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")
输出
loremipsum
dolorsant
amet:
total: 3
其他回答
或者没有闭包,你可以在Swift 2中这样做:
let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])
斯威夫特4
let words = "these words will be elements in an array".components(separatedBy: " ")
Xcode 8.0/Swift 3
let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")
var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last
漫长的道路:
var fullName: String = "First Last"
fullName += " " // this will help to see the last word
var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array
for Character in fullName.characters {
if Character == " " {
fullNameArr.append(newElement)
newElement = ""
} else {
newElement += "\(Character)"
}
}
var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last
最简单的方法是使用组件SeparatedBy:
对于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]
在解释Don Vaughn的答案时,我喜欢使用正则表达式。我很惊讶这只是Regex的第二个答案。然而,如果我们能用一个拆分方法而不是多个方法来解决这个问题,那就太好了。
我也受到了米特拉·辛加姆(Mithra Singam)的《答案》(Answer)的启发,排除了所有标点符号和空格。然而,不得不创建一个不允许的角色列表并没有引起我的共鸣。
\w-字母或数字符号的正则表达式。没有标点符号。
let foo = "(..# Hello,,(---- World ".split {
String($0).range(of: #"\w"#, options: .regularExpression) == nil
}
print(foo) // Prints "Hello World"
让我们假设你对Unicode不太满意。ASKII字母和数字怎么样?
let bar = "(..# Hello,,(---- World ".split {
!($0.isASCII && ($0.isLetter || $0.isNumber))
}
print(bar) // Prints "Hello World"