Swift – Split a String by Character Separator

To split a String by Character separator in Swift, use String.split() function. Call split() function on the String and pass the separator (character) as argument.

The syntax to split the String str with separator character ch is

str.split(separator: ch)

split() function returns a String Array with the splits as elements.

Example

In this example, we will take a string in variable str and separator character in variable ch. Using String.split() function, we will split the string str using ch separator.

main.swift

import Foundation

var str = "ab-cde-gh-ijkl"
var ch = Character("-")
var result = str.split(separator: ch)
print("Result : \(result)")

Output

Result : ["ab", "cde", "gh", "ijkl"]

We can also specify the maximum number of splits to happen for the given string.

main.swift

import Foundation

var str = "ab-cde-gh-ijkl"
var ch = Character("-")
var result = str.split(separator: ch, maxSplits: 2)
print("Result : \(result)")

Output

Result : ["ab", "cde", "gh-ijkl"]

Please observe that only two splits happened for the given string, resulting in three parts or elements in the returned array.

ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to split a string using String.split() function.