Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String into an array in Swift?

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.

like image 569
blee908 Avatar asked Sep 05 '14 03:09

blee908


People also ask

How do I split a string into an array of strings in Swift?

To split a string to an array in Swift by a character, use the String. split(separator:) function. However, this requires that the separator is a singular character, not a string.

How do I split a string in Swift?

Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.

How do I remove a character from a string in Swift?

Null Character ( \0 )

What is reduce in Swift?

reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.


2 Answers

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] 
like image 173
Chen-Tsu Lin Avatar answered Sep 20 '22 22:09

Chen-Tsu Lin


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  
like image 39
Ethan Avatar answered Sep 22 '22 22:09

Ethan