如何在Swift中按空格拆分字符串

50
let string = "hello hi"
var hello = ""
var hi = ""

我想要分割字符串,以便将 hello 的值变为 "hello",将 hi 的值变为 "hi"。
2个回答

127

试试这个:

var myString: String = "hello hi";
var myStringArr = myString.componentsSeparatedByString(" ")

myString 是你的字符串的名称,myStringArr 包含由空格分隔的组件。

那么你可以按以下方式获取组件:

var hello: String = myStringArr [0]
var hi: String = myStringArr [1]

文档:componentsSeparatedByString

编辑:对于Swift 3,以上内容应为:

var myStringArr = myString.components(separatedBy: " ")

Doc: components(separatedBy:)


很棒的答案。最简单的方式。 - Mehmet
以上在Swift 3中已经发生了变化,现在是:'var arrayOfSeperatedParts = myOriginalString.components(separatedBy: "insertSeperatorHere")' - Dave G
杰出的...... - M Hamayun zeb

28

这里有一个split函数,它接收正则表达式,您可以定义扩展以备将来使用:

Swift 4

extension String {

    func split(regex pattern: String) -> [String] {

        guard let re = try? NSRegularExpression(pattern: pattern, options: [])
            else { return [] }

        let nsString = self as NSString // needed for range compatibility
        let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
        let modifiedString = re.stringByReplacingMatches(
            in: self,
            options: [],
            range: NSRange(location: 0, length: nsString.length),
            withTemplate: stop)
        return modifiedString.components(separatedBy: stop)
    }
}

例子:

let string1 = "hello world"
string1.split(regex: " ")    // ["hello", "world"]

let string2 = "hello    world"
string2.split(regex: "[ ]+")  // ["hello", "world"]

Swift 2.2

extension String {

    func split(regex pattern: String) -> [String] {

        guard let re = try? NSRegularExpression(pattern: pattern, options: []) 
            else { return [] }

        let nsString = self as NSString // needed for range compatibility
        let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
        let modifiedString = re.stringByReplacingMatchesInString(
            self,
            options: [],
            range: NSRange(location: 0, length: nsString.length),
            withTemplate: stop)
        return modifiedString.componentsSeparatedByString(stop)
    }
}

Swift 2.0

extension String {

    // java, javascript, PHP use 'split' name, why not in Swift? :)
    func split(regex: String) -> Array<String> {
        do{
            let regEx = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions())
            let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
            let nsString = self as NSString // needed for range compatibility
            let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(), range: NSRange(location: 0, length: nsString.length), withTemplate:stop)
            return modifiedString.componentsSeparatedByString(stop)
        } catch {
            return []
        }
    }
}

Swift 1.1

extension String {

    // java, javascript, PHP use 'split' name, why not in Swift? :)
    func split(splitter: String) -> Array<String> {
        let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)
        let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
        let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
            range: NSMakeRange(0, countElements(self)),
            withTemplate:stop)
        return modifiedString.componentsSeparatedByString(stop)
    }
}

示例:

let string1 = "hello world"

string1.split(" ")    // ["hello", "world"]

let string2 = "hello    world"

string2.split("[ ]+")  // ["hello", "world"]

3
请描述 @downvoter。 - Maxim Shoustin
我没有给它点踩。我知道这种方法的缺点:你无法确定参数是普通字符串还是正则表达式模式字符串。比如,如果我想按"\d+"(字面字符串,而不是正则表达式)来分割一个字符串,该怎么办呢? - Tyler Liu
1
@TylerLong 这个方法告诉你它是一个正则表达式。如果你想按照字面意义 "\d+" 进行分割,那么你需要传入一个描述该字面字符串的正则表达式。例如:"\\\\d\\+" - masukomi
我建议将该方法重命名为func split(regex pattern: String) -> [String],这样在调用时就可以写成string1.split(regex: " ")。("pattern"是因为regex应该是NSRegularExpression)现有的CollectionType.split也可以接受单个字符,所以当参数仅为" "时很难确定调用哪一个。 - ctietze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接