THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This article explains about multiple ways to split a string into array in swift 2,3 and 4 with examples
There are multiple ways we can do
In the Swift 2
version, You can use the componentsSeparatedByString
of a string.
It returns an array of substrings.
import Foundation
var name: String = "Hello Welcome to cb "
let substrings = name.componentsSeparatedByString(" ")
print(substrings[0]);
print(substrings[1]);
print(substrings[2]);
In The Swift 3
version,
You can use the String components method which accepts separatedBy parameters with blank space.
components return the array of substring split by space.
You can access array elements using the index mechanism
import Foundation
var name: String = "first middle last"
let nameArray = name.components(separatedBy: " ")
var firstName: String = nameArray[0]
var middleName: String = nameArray[1]
var lastName: String = nameArray[2]
print(firstName); //first
print(middleName); //middle
print(lastName); //last
In The Swift 4
version, You can use the split method
of a String.
import Foundation
var name: String = "Hello Welcome to cb "
let substrings = name.split(separator: " ")
print(substrings)
Output:
["Hello", "Welcome", "to", "cb"]
You can also split with any characters using the above methods based on the Swift version.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts