In Swift, you can split a string into an array by using the split() method.
The split() method
Syntax:
func split(separator: Character,
maxSplits: Int = default,
omittingEmptySubsequences: Bool = default) -> [Substring]
Where:
- separator: The separator character to split the string. It can be any Character type, such as a space, comma, or newline character.
- maxSplits (optional): The maximum number of splits to perform. By default, all occurrences of the separator character are split. If maxSplits is specified, the method stops splitting the string after the specified number of splits is reached.
- omittingEmptySubsequences (optional): A boolean value that determines whether empty substrings should be included in the resulting array. By default, empty substrings are included. If omittingEmptySubsequences is set to true, empty substrings are excluded.
Now, it’s time to write some code.
Examples
Splitting a string into an array of words
If you want to split a string into an array of words, you can use the split() method with the default separator of whitespace characters:
let str = "This is a mediocre sentence"
let words = str.split(separator: " ")
print(words)
Output:
["This", "is", "a", "mediocre", "sentence"]
Splitting a string into an array of lines
In case you want to split a string into an array of lines (i.e., separate the string at each newline character), you can use the newline character \n as the separator, like this:
let str = "First line\nSecond line\nThird line"
let arr = str.split(separator: "\n")
print(arr)
Output:
["First line", "Second line", "Third line"]
Using the split() method with all of its parameters
let str = "apple,banana,orange"
let arr = str.split(separator: ",", maxSplits: 1, omittingEmptySubsequences: true)
print(arr)
Output:
["apple", "banana,orange"]
In this example, the split() method is called on the str string with a separator argument of “,”. The maxSplits parameter is set to 1, so the method stops splitting the string after the first occurrence of the separator. The omittingEmptySubsequences parameter is set to true, so empty substrings are excluded from the result.