Split a string into an array of substrings in Swift
This tutorial is all about splitting a given string into an array of substrings in Swift. Here we are provided with a string where we need to find its subsequences. There is a method called split() in Swift which consists of three parameters namely separator, maxSplits, and OmittingEmptySequence which accepts Character, integer, and bool values respectively. We are going to use this function to complete this task.
Given a string:
"Sun rises in the East"
The output should be like an array of substrings as=
["Sun", "rises", "in", "the", "East"]
Starting with creating a string in Swift follow the snippet-
let strings="Sun rises in the East"
Using the split method with a separator(” “) would result in the desired output. The snippet part would be-
let substring=strings.split(separator: " ")
So we have stored the result in the substring, now we need to print the substring as-
Sometimes we need to split up into particular numbers. Say for example 2 so we will set
maxSplits:2 which will result in
["Sun", "rises", "in the East"] if you want to omit the Empty space, by default this parameter is set to true and it won’t return null values but if you want to include the null spaces in your output, you need to set this parameter to false then your output will include an empty string too.
The complete code:
let strings="Sun rises in the East" let substring=strings.split(separator: " ") print(substring)
Output- ["Sun", "rises", "in", "the", "East"]
So we have built a code in Swift to split a string into an array of substrings using the split() method.