Concatenating and Splitting Strings in Swift
In this article, we will go over how to concatenate and split strings in Swift.
Concatenating Strings
When you want to concatenate strings in Swift, you can use the + operator, the += operator, or string interpolation.
Let's try these three methods to concatenate the string variables greet and name as shown below.
var greet = "Hello"
let name = "Emily"
let string1 = greet + ", " + name + "!"
let string2 = "\(greet), \(name)!"
greet += ", "
greet += name
greet += "!"
let string3 = greet
print(string1)
print(string2)
print(string3)
The output looks like this. The values of string1, string2, and string3 are the same, each showing the concatenated string.
Hello, Emily!
Hello, Emily!
Hello, Emily!
In this kind of case, string interpolation is usually the simplest and most intuitive approach.
Splitting Strings
To split a string in Swift, you can use the split() method.
The split() method takes the following parameters: separator, maxSplits, and omittingEmptySubsequences. It returns an array of Substring values, which are slices that point to the original string.
- separator: Required. Defines which character(s) to split on.
- maxSplits: Optional. Defines the maximum number of splits (default is the maximum Int value).
- omittingEmptySubsequences: Optional. Whether empty substrings should be omitted (default is true).
Let's try splitting a string with split().
let message = "My name is Emily. "
print(message.split(separator: " "))
print(message.split(separator: " ", maxSplits: 1))
The output shows that the string message is split on spaces. When maxSplits is set to 1, it splits only once.
["My", "name", "is", "Emily."]
["My", "name is Emily. "]
Splitting Strings into Arrays
The split() method in Swift returns an array of Substring values, which are slices pointing to the original string.
If you specifically want an array of String values, you can use the components() method from NSString.
The components() method takes only one parameter, separatedBy. Unlike split(), if there are empty substrings, they are included in the result. Since it is part of NSString, you will need to import Foundation.
import Foundation
let message = "My name is Emily. "
let splitResult1 = message.split(separator: " ")
let splitResult2 = message.components(separatedBy: " ")
print(splitResult1)
print(type(of: splitResult1))
print(splitResult2)
print(type(of: splitResult2))
The output looks like this. Notice that the result of components() is an array of String values.
["My", "name", "is", "Emily."]
Array<Substring>
["My", "name", "is", "Emily.", "", ""]
Array<String>
That is how to concatenate and split strings in Swift.