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

I wan't to split my string so that the value of hello get "hello" and the value of hi get "hi"

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Clément Bisaillon
  • 5,037
  • 8
  • 32
  • 53

2 Answers2

127

Try this:

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

Where myString is the name of your string, and myStringArr contains the components separated by the space.

Then you can get the components as:

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

Doc: componentsSeparatedByString

EDIT: For Swift 3, the above will be:

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

Doc: components(separatedBy:)

JosEduSol
  • 5,268
  • 3
  • 23
  • 31
  • The above has changed in Swift 3, it is now: 'var arrayOfSeperatedParts = myOriginalString.components(separatedBy: "insertSeperatorHere")' – Dave G Nov 29 '16 at 12:29
28

Here are split that receives regex as well. You can define extension for future usage:

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

Examples:

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

Examples:

let string1 = "hello world"

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

let string2 = "hello    world"

string2.split("[ ]+")  // ["hello", "world"]
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • 3
    @downvoter please describe – Maxim Shoustin Sep 13 '14 at 05:53
  • I didn't downvote. I know the disadvantage of the method: you don't known when the parameter is a plain string while when it is a regex pattern string. For example, what if I want to split a string by "\d+" (literal string, not regex) – Tyler Liu Nov 06 '15 at 10:35
  • 1
    @TylerLong the method tells you it's a regexp. If you want to split by the literal "\d+" then you pass in a regex that describes that literal string. E.g.: `"\\\\d\\+"` – masukomi Jan 14 '16 at 03:08
  • I'd suggest to rename the method to `func split(regex pattern: String) -> [String]` so on the call-site it's `string1.split(regex: " ")` instead. ("pattern" because the `regex` is supposed to be `NSRegularExpression`) The existing `CollectionType.split` can take a single character, too, so it's hard to tell which one is called when the parameter is `" "` only. – ctietze Jun 16 '16 at 11:11