web-dev-qa-db-fra.com

Comment diviser une chaîne en Swift

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

Je ne veux pas diviser ma chaîne pour que la valeur de Hello soit "Bonjour" et la valeur de "Hi"

43
Clément Bisaillon

Essaye ça:

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

myString est le nom de votre chaîne et myStringArr contient les composants séparés par un espace.

Ensuite, vous pouvez obtenir les composants en tant que:

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

Doc: componentsSeparatedByString

EDIT: Pour Swift 3, ce qui précède sera:

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

Doc: composants (séparésPar:)

114
JosEduSol

Voici split qui reçoit regex également. Vous pouvez définir une extension pour une utilisation future:

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

Exemples:

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

Exemples:

let string1 = "hello world"

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

let string2 = "hello    world"

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