How to split a string in Swift

Clément Bisaillon
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"

JosEduSol

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related