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

var fullName: String = "First Last"

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

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

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

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


当前回答

假设您有一个名为“Hello World”的变量,如果您想将其拆分并存储为两个不同的变量,可以这样使用:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").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]

空白问题

一般来说,人们会一次又一次地重复这个问题和糟糕的解决方案。这是一个空间吗?“”以及“\n”、“\t”或一些您从未见过的unicode空白字符,在很大程度上是不可见的。虽然你可以逃脱

弱解决方案

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

如果你需要在现实中动摇你的控制,请观看WWDC视频中的字符串或日期。简而言之,让苹果解决这类平凡的任务几乎总是更好的。

稳健的解决方案:使用NSCharacterSet

IMHO,正确做到这一点的方法是使用NSCharacterSet,因为正如前面所述,您的空白可能不是您所期望的,并且Apple提供了一个空白字符集。要探索提供的各种字符集,请查看Apple的NSCharacterSet开发人员文档,然后,如果不符合您的需要,才可以扩充或构建新的字符集。

NSCharacterSet空白

返回包含Unicode常规中的字符的字符集Z类和字符表(U+0009)。

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

字符串处理在Swift中仍然是一个挑战,而且它一直在显著变化,从其他答案中可以看到。希望事情稳定下来,事情会变得更简单。这是在当前3.0版本的Swift中使用多个分隔符的方法。

斯威夫特3:

let chars = CharacterSet(charactersIn: ".,; -")
let split = phrase.components(separatedBy: chars)

// Or if the enums do what you want, these are preferred. 
let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etc
let split2 = phrase.components(separatedBy: chars2)

这里是我刚刚构建的一个算法,它将通过数组中的任何字符分割字符串,如果有任何希望保留具有分割字符的子字符串,可以将swall参数设置为true。

Xcode 7.3-Swift 2.2:

extension String {

    func splitBy(characters: [Character], swallow: Bool = false) -> [String] {

        var substring = ""
        var array = [String]()
        var index = 0

        for character in self.characters {

            if let lastCharacter = substring.characters.last {

                // swallow same characters
                if lastCharacter == character {

                    substring.append(character)

                } else {

                    var shouldSplit = false

                    // check if we need to split already
                    for splitCharacter in characters {
                        // slit if the last character is from split characters or the current one
                        if character == splitCharacter || lastCharacter == splitCharacter {

                            shouldSplit = true
                            break
                        }
                    }

                    if shouldSplit {

                        array.append(substring)
                        substring = String(character)

                    } else /* swallow characters that do not equal any of the split characters */ {

                        substring.append(character)
                    }
                }
            } else /* should be the first iteration */ {

                substring.append(character)
            }

            index += 1

            // add last substring to the array
            if index == self.characters.count {

                array.append(substring)
            }
        }

        return array.filter {

            if swallow {

                return true

            } else {

                for splitCharacter in characters {

                    if $0.characters.contains(splitCharacter) {

                        return false
                    }
                }
                return true
            }
        }
    }
}

例子:

"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]

非顶部:

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

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

}