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.
Sometimes, We want a string to be split into substring and converted into an array.
The string can be split based on a delimiter such as space or comma.
import Foundation
let str : String = "first middle last";
let strArray = str.components(separatedBy: [" "])
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>
using String split with separator
The string contains a split with separator value, convert into an array. split is a function introduced in the Swift 4 version
let str : String = "first middle last";
let strArray = str.split(separator: " ")
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>
Output:
["first", "middle", "last"]
Array<Substring>
Another way using the whereSeparator in the split function
import Foundation
let str : String = "first middle last";
let strArray = str.split(whereSeparator: {$0 == " "})
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>
🧮 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