By blee908


2014-09-05 03:51:01 8 Comments

Say I have a string here:

var fullName: String = "First Last"

I want to split the string base on white space and assign the values to their respective variables

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

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

Also, sometimes users might not have a last name.

30 comments

@iOS 2018-09-17 06:57:50

In Swift 4.2 and Xcode 10

//This is your str
let str = "This is my String" //Here replace with your string

Option 1

let items = str.components(separatedBy: " ")//Here replase space with your value and result is Array.
//Direct line of code
//let items = "This is my String".components(separatedBy: " ")
let str1 = items[0]
let str2 = items[1]
let str3 = items[2]
let str4 = items[3]
//OutPut
print(items.count)
print(str1)
print(str2)
print(str3)
print(str4)
print(items.first!)
print(items.last!)

Option 2

let items = str.split(separator: " ")
let str1 = String(items.first!)
let str2 = String(items.last!)
//Output
print(items.count)
print(items)
print(str1)
print(str2)

Option 3

let arr = str.split {$0 == " "}
print(arr)

Option 4

By Apple Documentation....

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " "))
print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts
print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts
print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.
print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.
print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))
print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))

@Leo Dabus 2015-01-09 22:50:40

Xcode 9 Swift 4 or Xcode 8.2.1 • Swift 3.0.2

If you just need to properly format a person name, you can use PersonNameComponentsFormatter.

The PersonNameComponentsFormatter class provides localized representations of the components of a person’s name, as represented by a PersonNameComponents object. Use this class to create localized names when displaying person name information to the user.


// iOS (9.0 and later), macOS (10.11 and later), tvOS (9.0 and later), watchOS (2.0 and later)
let nameFormatter = PersonNameComponentsFormatter()

let name =  "Mr. Steven Paul Jobs Jr."
// personNameComponents requires iOS (10.0 and later)
if let nameComps  = nameFormatter.personNameComponents(from: name) {
    nameComps.namePrefix   // Mr.
    nameComps.givenName    // Steven
    nameComps.middleName   // Paul
    nameComps.familyName   // Jobs
    nameComps.nameSuffix   // Jr.

    // It can also be configured to format your names
    // Default (same as medium), short, long or abbreviated

    nameFormatter.style = .default
    nameFormatter.string(from: nameComps)   // "Steven Jobs"

    nameFormatter.style = .short
    nameFormatter.string(from: nameComps)   // "Steven"

    nameFormatter.style = .long
    nameFormatter.string(from: nameComps)   // "Mr. Steven Paul Jobs jr."

    nameFormatter.style = .abbreviated
    nameFormatter.string(from: nameComps)   // SJ

    // It can also be use to return an attributed string using annotatedString method
    nameFormatter.style = .long
    nameFormatter.annotatedString(from: nameComps)   // "Mr. Steven Paul Jobs jr."
}

enter image description here

@Rakesh 2018-09-21 07:12:28

This really Good API provided by Apple and good explained.+1

@Mohammed Abunada 2018-12-06 15:08:32

This is for String and CSV file for swift 4.2 at 20181206 1610

var dataArray : [[String]] = []
 let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
        let url = URL(fileURLWithPath: path!)
        do {
            let data = try Data(contentsOf: url) 
            let content = String(data: data, encoding: .utf8)
            let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
           for line in parsedCSV!
            {
                dataArray.append(line)
           }
        }
        catch let jsonErr {
            print("\n   Error read CSV file: \n ", jsonErr)
        }

            print("\n MohNada 20181206 1610 - The final result is \(dataArray)  \n ")

@blackstorm 2018-12-03 07:06:22

You can use this common function and add any string which you want to separate

func separateByString(String wholeString: String, byChar char:String) -> [String] {

    let resultArray = wholeString.components(separatedBy: char)
    return resultArray
}

var fullName: String = "First Last"
let array = separateByString(String: fullName, byChar: " ")
var firstName: String = array[0]
var lastName: String = array[1]
print(firstName)
print(lastName)

@ayaio 2018-12-03 18:07:21

Hi. In Swift, parameters name should always start with lowercase. Like: separateByString(string wholeString: String, byChar char:String). Also this way avoids conflating the variable name with a type.

@AamirR 2018-08-18 10:15:10

I was looking for loosy split, such as PHP's explode where empty sequences are included in resulting array, this worked for me:

"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)

Output:

["First", ""]

@Xcodian Solangi 2018-08-03 07:01:45

Swift 4, Xcode 10 and iOS 12 Update 100% working

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullnameArr[1] //Last

See the Apple's documentation here for further information.

@MrMins 2018-07-30 22:54:52

Swift 4

let string = "loremipsum.dolorsant.amet:"

let result = string.components(separatedBy: ".")

print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")

Output

loremipsum
dolorsant
amet:
total: 3

@Jeroen Zonneveld 2017-06-07 17:21:15

Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Example: let s = "hi, hello" let a = s.split(separator: ",") print(a)

Now you got an array with 'hi' and ' hello'.

@Supertecnoboff 2018-03-30 15:37:11

Thanks for this answer, so helpful. I love how Swift 4 is making syntax short and easy.

@Parth Barot 2018-05-02 12:55:18

Let's say you have a variable named "Hello World" and if you want to split it and store it into two different variables you can use like this:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last

@Vidhyapathi Kandhasamy 2018-05-02 08:35:27

Hope this is helpfull

Swift 4: Split a String into an array. Step 1: assign string. step 2: based on @ spliting. Note: variableName.components(separatedBy: "split keyword")

let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."
let fullNameArr = fullName.components(separatedBy: "@")
print("split", fullNameArr)

@CodeBender 2017-01-07 18:07:35

I had a scenario where multiple control characters can be present in the string I want to split. Rather than maintain an array of these, I just let Apple handle that part.

The following works with Swift 3.0.1 on iOS 10:

let myArray = myString.components(separatedBy: .controlCharacters)

@jnblanchard 2018-04-09 16:38:23

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"
  • Disallow same first and last name
  • If a fullname is invalid, take placeholder value "John Doe"

@Cameron Lowell Palmer 2016-01-01 20:34:02

The whitespace issue

Generally, people reinvent this problem and bad solutions over and over. Is this a space? " " and what about "\n", "\t" or some unicode whitespace character that you've never seen, in no small part because it is invisible. While you can get away with

A weak solution

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

If you ever need to shake your grip on reality watch a WWDC video on strings or dates. In short, it is almost always better to allow Apple to solve this kind of mundane task.

Robust Solution: Use NSCharacterSet

The way to do this correctly, IMHO, is to use NSCharacterSet since as stated earlier your whitespace might not be what you expect and Apple has provided a whitespace character set. To explore the various provided character sets check out Apple's NSCharacterSet developer documentation and then, only then, augment or construct a new character set if it doesn't fit your needs.

NSCharacterSet whitespaces

Returns a character set containing the characters in Unicode General Category Zs and CHARACTER TABULATION (U+0009).

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

@Nicolas Miari 2016-07-01 02:23:58

Agreed. The first thing that occurred to me after seeing the answers that split by " " is: What happens if the input text contains several consecutive spaces? What if it has tabs? Full-width (CJK) space? etc.

@Farini 2018-08-23 19:31:22

Definitely the best answer here.

@Bobby 2017-06-12 20:38:48

Swift 4

let words = "these words will be elements in an array".components(separatedBy: " ")

@aeid 2017-12-17 12:21:02

Xcode 9.2 there is no components method on strings

@Annjawn 2017-12-26 10:13:15

@aeid yes there is. Bobby's answer is valid.

@aeid 2018-03-09 14:36:40

@Annjawn hmm I'm not sure why it was not showing earlier.

@Annjawn 2018-03-10 20:04:10

@aeid this happens if the project is pre building or simply building while you are typing your code.

@tepl 2017-09-16 19:36:02

Swift 3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • Returns three strings AAA, BBB and CCC
  • Filters out empty fields
  • Handles multiple spaces and tabulation characters
  • If you want to handle new lines, then replace .whitespaces with .whitespacesAndNewlines

@WMios 2014-09-05 04:09:06

The easiest method to do this is by using componentsSeparatedBy:

For 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]

For 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]

@NRitH 2015-02-17 18:30:28

Is this documented anywhere, Maury? What if I need to split on something other than a single character?

@rmp251 2015-05-13 22:56:17

@NRitH consider .componentsSeparatedByCharactersInSet(.whitespaceAndNewlineC‌​haracterSet())

@rmp251 2015-07-16 23:43:57

@Crashalot there are two functions: componentsSeparatedByString and componentsSeparatedByCharactersInSet

@Daniel Springer 2018-12-02 03:12:27

How to split in max N parts?

@WMios 2018-12-02 09:26:34

@DaniSpringer, this question is more than 4 years old - ask a new question

@Vadim Bulavin 2017-07-12 09:26:53

I haven't found the solution that would handle names with 3 or more components and support older iOS versions.

struct NameComponentsSplitter {

    static func split(fullName: String) -> (String?, String?) {
        guard !fullName.isEmpty else {
            return (nil, nil)
        }
        let components = fullName.components(separatedBy: .whitespacesAndNewlines)
        let lastName = components.last
        let firstName = components.dropLast().joined(separator: " ")
        return (firstName.isEmpty ? nil : firstName, lastName)
    }
}

Passed test cases:

func testThatItHandlesTwoComponents() {
    let (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Smith")
    XCTAssertEqual(firstName, "John")
    XCTAssertEqual(lastName, "Smith")
}

func testThatItHandlesMoreThanTwoComponents() {
    var (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Smith")
    XCTAssertEqual(firstName, "John Clark")
    XCTAssertEqual(lastName, "Smith")

    (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Jr. Smith")
    XCTAssertEqual(firstName, "John Clark Jr.")
    XCTAssertEqual(lastName, "Smith")
}

func testThatItHandlesEmptyInput() {
    let (firstName, lastName) = NameComponentsSplitter.split(fullName: "")
    XCTAssertEqual(firstName, nil)
    XCTAssertEqual(lastName, nil)
}

@LugiHaue 2016-11-21 18:12:26

Swift Dev. 4.0 (May 24, 2017)

A new function split in Swift 4 (Beta).

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

Output:

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

Accessing values:

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

Xcode 8.1 / Swift 3.0.1

Here is the way multiple delimiters with array.

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

Output:

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

@Adrian 2017-02-06 23:46:31

Make sure to add import Foundation to the class you're using this in. #SavedYouFiveMinutes

@OderWat 2017-08-21 22:41:01

Attention (Swift 4): If you have a string like let a="a,,b,c" and you use a.split(separator: ",") you get an array like ["a", "b", c"] by default. This can be changed using omittingEmptySubsequences: false which is true by default.

@pkamb 2018-09-07 00:35:14

Any multi-character splits in Swift 4+?

@possen 2017-04-13 19:03:22

String handling is still a challenge in Swift and it keeps changing significantly, as you can see from other answers. Hopefully things settle down and it gets simpler. This is the way to do it with the current 3.0 version of Swift with multiple separator characters.

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)

@DonVaughn 2016-06-21 11:45:44

Most of these answers assume the input contains a space - not whitespace, and a single space at that. If you can safely make that assumption, then the accepted answer (from bennett) is quite elegant and also the method I'll be going with when I can.

When we can't make that assumption, a more robust solution needs to cover the following siutations that most answers here don't consider:

  • tabs/newlines/spaces (whitespace), including recurring characters
  • leading/trailing whitespace
  • Apple/Linux (\n) and Windows (\r\n) newline characters

To cover these cases this solution uses regex to convert all whitespace (including recurring and Windows newline characters) to a single space, trims, then splits by a single space:

Swift 3:

let searchInput = "  First \r\n \n \t\t\tMiddle    Last "
let searchTerms = searchInput 
    .replacingOccurrences(
        of: "\\s+",
        with: " ",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy: " ")

// searchTerms == ["First", "Middle", "Last"]

@NikaE 2016-11-04 19:29:46

Xcode 8.0 / Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

Long Way:

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

@Chen-Tsu Lin 2014-09-05 04:12:58

Just call componentsSeparatedByString method on your fullName

import Foundation

var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")

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

Update for Swift 3+

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]

@Brian 2015-05-27 14:42:07

This answer is much more elegant than the accepted one. Programmers from Taiwan are awesome :D

@Can 2015-05-31 09:06:21

Be noted that this is actually an underlying NSString (Swift automatically swaps them when importing Foundation).

@elcuco 2015-06-17 14:02:00

Which is no longer the case in Swift 1.2, in which Apple no longer converts Swift's String into NSString automagically.

@kellyfj 2015-06-22 19:53:22

I agree that this should be the accepted answer - much cleaner and simpler answer.

@Crashalot 2015-07-16 00:10:02

Is there an advantage to the accepted answer over this one?

@Frizlab 2015-07-18 07:34:59

@Crashalot This answer does not work starting from Swift 1.2.

@Andrew 2015-07-21 22:31:14

This answer works in Xcode 7 beta 4 and Swift 2.0. Xcode now auto-completes Foundation methods on Swift String objects without type casting to an NSString, which is not the case in Xcode 6.4 with Swift 1.2.

@KTPATEL 2015-09-29 07:22:56

this doesn't work in Swift 2: Xcode 7

@Velizar Hristov 2015-10-06 13:10:01

It didn't work in the REPL until I imported Foundation.

@Jon Cox 2016-01-27 14:23:32

This works exactly as expected (i.e. fullNameArr is an [String]) in Xcode 7.2.

@sterling archer 2016-02-29 05:01:20

this may be 1000x better than the accepted answer... nicely done

@Bob Spryn 2016-04-29 21:21:10

Array subscript doesn't return optionals. var lastName: String? = fullNameArr[1] will not work.

@Maxime Chéramy 2016-05-18 06:00:33

It apparently requires Foundation to work, which is no longer available in Swift 2.2.1 on Linux.

@Chad 2016-12-27 22:06:05

Using Swift 3 and XCode 8.2, I did not need to import Foundation.

@xxmbabanexx 2017-02-26 05:10:20

Is there a way to split using regex? I tried to do string.components(separatedBy: regex, options: .regularExpression) but I got an error.

@Daniel Springer 2018-12-02 03:11:56

How to limit amount of parts string splits to?

@Ethan 2014-10-09 05:06:46

The Swift way is to use the global split function, like so:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

with Swift 2

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last 

@Casey Perkins 2014-11-25 13:58:13

In my tests, componentsSeparatedByString is usually significantly faster, especially when dealing with strings that require splitting into many pieces. But for the example listed by the OP, either should suffice.

@Pascal 2015-01-07 15:46:39

As of Xcode 6.2b3 split can be used as split("a:b::c:", {$0 == ":"}, maxSplit: Int.max, allowEmptySlices: false).

@NRitH 2015-02-17 18:29:01

Just remember that you still need to use the old componentsSeparatedByString() method if your separator is anything longer than a single character. And as cool as it would be to say let (firstName, lastName) = split(fullName) {$0 == ' '}, that doesn't work, sadly.

@Pieter Meiresone 2015-04-19 01:23:55

@chrisco Could you say why this solution is preferred over the componentsSeparatedByString approach ? Regards

@Kashif 2015-05-19 18:37:09

@Ethan: If I want to use either "," or ";" as split characters, how can I modify your code?

@Ethan 2015-05-20 05:04:06

@Kashif then you could use split("a,b;c,d") {$0 == "," || $0 == ";"} or split("a,b;c,d") {contains(",;", $0)}

@Lars Blumberg 2015-09-16 16:12:38

This answer doesn't wirk anymore as of Xcode7 beta5, see answers below

@skagedal 2015-09-22 19:35:05

Correct code for Xcode 7.0 is let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init). Tried to edit, but it got rejected.

@KTPATEL 2015-09-29 07:17:45

for Swift 2: Xcode 7, fullNameArr[0] and fullNameArr[1] returns characterview

@John Tracid 2015-10-01 11:20:40

Answer need to be updated with comment from @skagedal because otherwise you have CharacterView instead of string but question was about string.

@sudo 2015-10-20 22:13:04

Geez, can't they make a .split() function like in Python already?

@sudo 2015-11-01 04:50:34

The method for Xcode 7.0 no longer works in Xcode 7.1.

@Kashif 2015-11-02 21:18:40

@Ethan: How can I split on "; " It only seems to allow one character for split?

@Cody Weaver 2015-12-13 01:07:35

Using XCode 7.2 I got an error and I think @LeoDabus answer is more Swift.

@Yifei He 何一非 2015-12-13 02:37:49

Anyone know how to split with more than 1 character? e.g. ". "

@brandonscript 2016-01-22 06:10:12

lol all the iterations of Swift 2...

@Lucas Goossen 2016-01-30 23:35:08

@JasonTyler wow, true, like 20x

@Josh 2016-02-16 16:48:35

Jeez!!!! APPLE! make up your mind!

@Suragch 2016-04-25 10:33:56

How about editing out the old stuff and just showing the current answer. People who need a history lesson can check the edit history.

@Honey 2016-08-16 16:27:15

Can you add explanation to your Syntax usage? What is $0 == " "?

@owlswipe 2016-11-24 20:21:40

Downvoted until you update for swift 3. Just copy Chen's answer below.

@Puji Wahono 2018-07-02 04:54:17

Good Job , swift 4 Just Copy

@Aqib Mumtaz 2016-06-02 12:38:19

Swift 2.2 Error Handling & capitalizedString Added :

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}

@DevAndArtist 2016-05-09 18:10:39

Here is an algorithm I just build, which will split a String by any Character from the array and if there is any desire to keep the substrings with splitted characters one could set the swallow parameter to 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
            }
        }
    }
}

Example:

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

@Gautam Sareriya 2016-04-26 14:21:45

As per Swift 2.2

You just write 2 line code and you will get the split string.

let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1]) 

Enjoy. :)

@ayaio 2016-04-26 14:24:14

Same answer as stackoverflow.com/a/25678505/2227743 on this page. Please read the other answers before posting yours. Thank you.

@Amr Lotfy 2016-04-07 08:12:54

let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

@Antonio 2014-09-05 06:42:51

As an alternative to WMios's answer, you can also use componentsSeparatedByCharactersInSet, which can be handy in the case you have more separators (blank space, comma, etc.).

With your specific input:

let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["First", "Last"]

Using multiple separators:

let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["Last", "First", "Middle"]

@Chris 2015-06-04 13:29:39

Most useful answer in my view, since you might want to allow separation of strings with , or ; or any other separator

@sudo 2016-04-05 05:35:10

This is WAY easier than the accepted answer!

@Confused 2016-10-06 21:21:14

SOLID FIND! Is there a good resource on learning what can be done with Swift Strings, beyond trawling headers?

@Koen 2016-12-05 01:33:59

This is avery nice write-up: oleb.net/blog/2016/08/swift-3-strings

@Sruit A.Suk 2015-03-12 12:11:19

I found an Interesting case, that

method 1

var data:[String] = split( featureData ) { $0 == "\u{003B}" }

When I used this command to split some symbol from the data that loaded from server, it can split while test in simulator and sync with test device, but it won't split in publish app, and Ad Hoc

It take me a lot of time to track this error, It might cursed from some Swift Version, or some iOS Version or neither

It's not about the HTML code also, since I try to stringByRemovingPercentEncoding and it's still not work

addition 10/10/2015

in Swift 2.0 this method has been changed to

var data:[String] = featureData.split {$0 == "\u{003B}"}

method 2

var data:[String] = featureData.componentsSeparatedByString("\u{003B}")

When I used this command, it can split the same data that load from server correctly


Conclusion, I really suggest to use the method 2

string.componentsSeparatedByString("")

@rickster 2015-07-29 19:08:48

I'd say this is close to "not an answer" status, in that it's mostly commentary on existing answers. But it is pointing out something important.

@abinop 2015-10-01 06:19:41

For swift 2, XCode 7.1:

let complete_string:String = "Hello world"
let string_arr =  complete_string.characters.split {$0 == " "}.map(String.init)
let hello:String = string_arr[0]
let world:String = string_arr[1]

@Elad Nava 2015-11-09 23:32:48

Any specific reason this was downvoted? Seems to work for me as well in Xcode 7.1.

Related Questions

Sponsored Content

46 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

48 Answered Questions

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

80 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

19 Answered Questions

[SOLVED] Why is char[] preferred over String for passwords?

18 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

57 Answered Questions

[SOLVED] What is the difference between String and string in C#?

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2078223 View
  • 2767 Score
  • 76 Answer
  • Tags:   c++ string split

33 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3384571 View
  • 1408 Score
  • 33 Answer
  • Tags:   java string

33 Answered Questions

[SOLVED] How do I split a string on a delimiter in Bash?

Sponsored Content