Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift String split()
In this tutorial, we will learn about the Swift String split() method with the help of examples.
The split() method breaks up a string at the specified separator and returns an array of strings.
Example
var text = "Swift is a fun programming language"
// split the text from space
print(text.split(separator: " "))
// Output: ["Swift", "is", "a", "fun", "programming", "language"]
split() Syntax
The syntax of split() is:
string.split(separator: Character, maxSplits: Int, ommittingEmptySequence: Bool)
Here, string is an object of the String class.
split() Parameters
The split() method can take three parameters:
- separator - Delimiter at which splits occur.
- maxSplits (optional) - Maximum number of splits. If not provided, there is no limit on the number of splits.
- omittingEmptySubsequences (optional) - specifies whether to omit empty string elements or to include them
Note: If maxSplits is specified, the array will have a maximum of maxSplits + 1 items.
split() Return Value
- returns an array of substrings
Example 1: Swift split()
var text = "Swift is awesome. Swift is fun."
// split at period "."
print(text.split(separator: "."))
// split string with limit
print(text.split(separator: " ", maxSplits: 2))
Output
["Swift is awesome", " Swift is fun"] ["Swift", "is", "awesome. Swift is fun."]
Example 2: split() with omittingEmptySubsequences Parameter
var text = "Swift is a fun programming language"
// split the text from space
// returned array doesn't contain empty string
print(text.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: true))
// returned array contains empty string
print(text.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: false))
Output
["Swift", "is", "a fun programming language"] ["Swift", "", "is a fun programming language"]
Did you find this article helpful?