假设我这里有一个字符串:

var fullName: String = "First Last"

我想在空白处拆分字符串,并将值分配给它们各自的变量

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

此外,有时用户可能没有姓氏。


当前回答

雨燕3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}

返回三个字符串AAA、BBB和CCC筛选出空字段处理多个空格和制表字符如果要处理新行,请将.whittespaces替换为.whittespace和新行

其他回答

Swift Dev.4.0(2017年5月24日)

Swift 4(Beta版)中拆分了一个新功能。

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

输出:

["Hello", "Swift", "4", "2017"]

访问值:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1/Swift 3.0.1

这是多个分隔符与数组的方式。

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

输出:

["12", "37", "2", "5"]

非顶部:

对于搜索如何使用子字符串(而不是字符)拆分字符串的人来说,下面是一个有效的解决方案:

// 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])
    }

}

作为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"]
var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last =  fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"

不允许使用相同的名字和姓氏如果全名无效,则取占位符值“John Doe”

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