split a string into an array of substrings in swift

In Swift, you can use the split method to split a string into an array of substrings based on a delimiter. Here's how you can do it:

main.swift
let str = "hello,world,how,are,you"
let substrings = str.split(separator: ",") // ["hello", "world", "how", "are", "you"]
122 chars
3 lines

In the above code, we first declare a string str which has commas as delimiters. Then we use the split method on this string by passing the delimiter , as a parameter to it. This returns an array of substrings substrings which are separated by commas.

You can also use the components(separatedBy:) method to split a string into an array of substrings based on a delimiter. Here's how you can do it:

main.swift
let str = "hello,world,how,are,you"
let substrings = str.components(separatedBy: ",") // ["hello", "world", "how", "are", "you"]
129 chars
3 lines

In the above code, we again declare a string str which has commas as delimiters. Then we use the components(separatedBy:) method on this string by passing the delimiter , as a parameter to it. This returns an array of substrings substrings which are separated by commas.

gistlibby LogSnag