假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
当前回答
非顶部:
对于搜索如何使用子字符串(而不是字符)拆分字符串的人来说,下面是一个有效的解决方案:
// TESTING
let str1 = "Hello user! What user's details? Here user rounded with space."
let a = str1.split(withSubstring: "user") // <-------------- HERE IS A SPLIT
print(a) // ["Hello ", "! What ", "\'s details? Here ", " rounded with space."]
// testing the result
var result = ""
for item in a {
if !result.isEmpty {
result += "user"
}
result += item
}
print(str1) // "Hello user! What user's details? Here user rounded with space."
print(result) // "Hello user! What user's details? Here user rounded with space."
print(result == str1) // true
/// Extension providing `split` and `substring` methods.
extension String {
/// Split given string with substring into array
/// - Parameters:
/// - string: the string
/// - substring: the substring to search
/// - Returns: array of components
func split(withSubstring substring: String) -> [String] {
var a = [String]()
var str = self
while let range = str.range(of: substring) {
let i = str.distance(from: str.startIndex, to: range.lowerBound)
let j = str.distance(from: str.startIndex, to: range.upperBound)
let left = str.substring(index: 0, length: i)
let right = str.substring(index: j, length: str.length - j)
a.append(left)
str = right
}
if !str.isEmpty {
a.append(str)
}
return a
}
/// the length of the string
public var length: Int {
return self.count
}
/// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
///
/// - parameter index: the start index
/// - parameter length: the length of the substring
///
/// - returns: the substring
public func substring(index: Int, length: Int) -> String {
if self.length <= index {
return ""
}
let leftIndex = self.index(self.startIndex, offsetBy: index)
if self.length <= index + length {
return String(self[leftIndex..<self.endIndex])
}
let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
return String(self[leftIndex..<rightIndex])
}
}
其他回答
斯威夫特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
我还没有找到能够处理3个或更多组件名称并支持较旧iOS版本的解决方案。
struct NameComponentsSplitter {
static func split(fullName: String) -> (String?, String?) {
guard !fullName.isEmpty else {
return (nil, nil)
}
let components = fullName.components(separatedBy: .whitespacesAndNewlines)
let lastName = components.last
let firstName = components.dropLast().joined(separator: " ")
return (firstName.isEmpty ? nil : firstName, lastName)
}
}
通过测试用例:
func testThatItHandlesTwoComponents() {
let (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Smith")
XCTAssertEqual(firstName, "John")
XCTAssertEqual(lastName, "Smith")
}
func testThatItHandlesMoreThanTwoComponents() {
var (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Smith")
XCTAssertEqual(firstName, "John Clark")
XCTAssertEqual(lastName, "Smith")
(firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Jr. Smith")
XCTAssertEqual(firstName, "John Clark Jr.")
XCTAssertEqual(lastName, "Smith")
}
func testThatItHandlesEmptyInput() {
let (firstName, lastName) = NameComponentsSplitter.split(fullName: "")
XCTAssertEqual(firstName, nil)
XCTAssertEqual(lastName, nil)
}
我在寻找loosy拆分,例如PHP的分解,其中空序列包含在结果数组中,这对我很有用:
"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)
输出:
["First", ""]
这直接提供了一个分割部分的数组
var fullNameArr = fullName.components(separatedBy:" ")
那么你可以这样使用,
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[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"]