In programming, a string is a way of referring to a sequence of characters, either as a literal constant or as a variable. Swift provides us with lots of functions to interact with them. In this chapter, we will dive into the Swift library for Strings and explore different ways to manipulate them efficiently.
7.1 Append character to string
Problem
I want to append a character to an existing string.
Solution
Let’s initialize our
Character.
let char : Character = "!"
First approach: Using the
+= operator.
var first = "Hello World"
first += String(char)
Second approach: Using the
append method
.
var second = "Hello World"
second.append(char)
How It Works
Appending a character to an existing string can be done either with the
+= operator (after converting the char to String) or using the Strings
append method – and works pretty much as with strings.
7.2 Append string to string
Problem
I want to append a string to another string.
Solution
First approach: Using the
+= operator.
var first = "Hello "
first += "World!"
Second approach: Using the
append method.
var second = "Hello "
second.append("World! - again")
How It Works
Appending a string to an existing string can be done either with the
+= operator
or using the Strings
append method.
Hello World!
Hello World! - again
7.3 Check if object is string
Problem
I want to check if a given object is of String type.
Solution
First, we initialize our example “object” – let’s make it a number.
Now, let’s see...
if a is String {
print("Yes, it's a string.")
} else {
print("Oh, no, this is not a string! Maybe it's a number?")
}
How It Works
To check if an object is of type String, we can use an
X is String statement
. (The same construct can also be used to check whether an object is of any other type.)
Oh, no, this is not a string! Maybe it's a number?
7.4 Check if string contains character
Problem
I want to check if a string contains a specific character.
Solution
First, we set some initial value.
let str = "Hello World"
let char : Character = "W"
Now, let’s see...
if str.contains(char) {
print("Well, yes, it contains the character '(char)'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string contains a given
character, we can use the String’s
contains method – pretty much as we’d do with arrays.
Well, yes, it contains the character 'W'...
7.5 Check if string contains RegEx
Problem
I want to check if a string contains a given regular expression.
Solution
This method either returns the range of the regex, or
nil - if the regex is not found.
First, we set some initial value.
Now, let’s look for a digit – any digit...
if str.range(of: "\d", options:.regularExpression) != nil {
print("Yes, I found a digit...")
} else {
print("Oops. No numbers found whatsoever...")
}
How It Works
In order to check if a string contains a
regular expression, we can use the String’s
range(of: options:) method
.
Oops. No numbers found whatsoever...
7.6 Check if string contains string
Problem
I want to check if a string contains another string.
Solution
This method either returns the range of the string, or
nil – if the string is not found.
First, we set some initial value.
Now, let’s see...
if str.range(of: "Hello") != nil {
print("Well, yes, it contains the word 'Hello'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string contains another string, we can use the Strings
range(of:) method
.
Well, yes, it contains the word 'Hello'...
7.7 Check if string ends with RegEx
Problem
I want to check if a string ends with a given regular expression.
Solution
Instead we can use the String’s ‘range(of:,options:)’ method, along with the appropriate regular expression syntax (
$).
First, we set some initial value.
Now, let’s see if it ends with “World.”
if str.range(of: "World$", options:.regularExpression) != nil {
print("Well, yes, it ends with 'World'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string ends with a specific regular expression, we can use its
range(of:options:) method
.
Well, yes, it ends with 'World'...
7.8 Check if string ends with string
Problem
I want to check if a string ends with a given string.
Solution
First, we set some initial value.
Now, let’s see...
if str.hasSuffix("World") {
print("Well, yes, it ends with 'World'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string has a specific suffix, we can use the String’s
hasSuffix method
.
Well, yes, it ends with 'World'...
7.9 Check if string is empty
Problem
I want to check if a string is empty.
Solution
First, we initialize our example string with some value.
Now, let’s see...
if a.isEmpty {
print("Our string is empty :(")
} else {
print("Of course it's not empty - here it is: (a)")
}
How It Works
To check if a string is empty, we can use its
isEmpty property
.
Of course it's not empty – here it is: Hello world!
7.10 Check if string starts with RegEx
Problem
I want to check if a string starts with a regular expression.
Solution
Instead we can use the String’s
range(of:,options:) method, along with the appropriate regular expression syntax (
^).
First, we set some initial value.
Now, let’s see if it begins with “Hello.”
if str.range(of: "^Hello", options:.regularExpression) != nil {
print("Well, yes, it starts with 'Hello'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string starts with a specific
regular expression, we cannot use the
range(of:options:) method
.
Well, yes, it starts with 'Hello'...
7.11 Check if string starts with string
Problem
I want to check if a string starts with another string.
Solution
First, we set some initial value.
Now, let’s see...
if str.hasPrefix("Hello") {
print("Well, yes, it starts with 'Hello'...")
} else {
print("Oops. Something went wrong!")
}
How It Works
In order to check if a string has a specific prefix, we can use the String’s hasPrefix method
.
Well, yes, it starts with 'Hello'...
7.12 Check if two strings are equal
Problem
I want to check if two strings are equal, that is: the same.
Solution
First, we initialize our strings.
let a = "first string"
let b = "second string"
Let’s see...
if a == b {
print("Yep, the strings are equal")
} else {
print("Nope, they are different strings")
}
How It Works
To compare two strings and check if they are
equal, we can use the
== comparison
operator.
Nope, they are different strings
7.13 Compare two strings
Problem
I want to compare two string lexicographically, that is: which one comes first in a dictionary.
Solution
First, we initialize our strings.
let a = "first string"
let b = "second string"
Let’s see...
if a < b {
print("A comes before B")
} else {
print("B comes before A")
}
How It Works
To compare two strings lexicographically, we can use the < and > comparison operators
.
7.14 Concatenate strings
Problem
I want to concatenate two different strings.
Solution
First, we set some initial values.
let first = "Hello "
let second = "World!"
Then, we concatenate them.
let greeting = first + second
How It Works
Concatenating two or more strings can be
done, using the
+ operator
.
7.15 Convert string to capitalized
Problem
I want to capitalize a given string, that is: convert the first character of each word to uppercase.
Solution
First, we set some initial value.
Then, we convert it.
let converted = str.capitalized
Let’s see...
print("'(str)' => '(converted)'")
How It Works
In order to convert a string to capitalized, that is to capitalize every single one of the words in it, we can use the String’s
capitalized property
.
'hello world' => 'Hello World'
7.16 Convert string to data
Problem
I want to convert a string to a Data object.
Solution
First, let’s set some test string.
let str = "This is my test string"
Then, we convert it to a
Data object.
if let data = str.data(using: .utf8) {
// And let's print it out (don't expect much!)
How It Works
In order to convert a Json string to a
Data object, we may use the String’s
data method.
7.17 Convert string to double
Problem
I want to extract a value from a String as a Double.
Solution
Let’s create our test string.
Let’s convert it to a
Double.
First, make sure nothing went wrong with the conversion.
How It Works
In order to convert a String to Double, we can easily use the
Double initializer
.
7.18 Convert string to float
Problem
I want to extract a value from a String as a Float.
Solution
Let’s create our test string.
Let’s convert it to a
Float.
First, make sure nothing went wrong with the conversion.
How It Works
In order to convert a String to Float, we can easily use the
Float initializer
.
7.19 Convert string to integer
Problem
I want to extract a value from a String as an Int.
Solution
Let’s create our test string.
Let’s convert it to an
Int.
First, make sure nothing went wrong with the conversion.
How It Works
In order to convert a String to Int, we can easily use the
Int initializer
.
7.20 Convert string to lowercase
Problem
I want to convert a given string to lowercase.
Solution
First, we set some initial value.
Then, we convert it.
let converted = str.lowercased()
Let’s see...
print("'(str)' => '(converted)'")
How It Works
In order to convert a string to lowercase, we can use the Strings
lowercased method
.
'Hello World' => 'hello world'
7.21 Convert string to uppercase
Problem
I want to convert a given string to uppercase.
Solution
First, we set some initial value.
Then, we convert it.
let converted = str.uppercased()
Let’s see...
print("'(str)' => '(converted)'")
How It Works
In order to convert a string to uppercase, we can use the Strings
uppercased method
.
'Hello World' => 'HELLO WORLD'
7.22 Create an empty string
Problem
I want to create an empty String.
Solution
First approach: Use the
"" empty string expression.
Second approach: Use the
String initializer.
Let’s print our two... empty strings – don’t expect too much.
How It Works
In order to create an empty string, it’s a piece of cake. Either initialize it, or use the
String constructor.
7.23 Create NSString from string
Problem
I want to create a String from an NSString object.
Solution
First, we initialize our example string.
Let’s convert it to an
NSString.
let b = NSString(string: str)
Let’s try using the
NSString’s
hash property (not available for Swift pure strings), to make
sure we made it.
print("Final string's hash: (b.hash)")
print("Yep, it's an NSString!")
How It Works
In order to convert/bridge a String to an NSString, for example, when you need to access APIs that expect data in an NSString instance, or need to use some NSString-specific methods, we can use the
NSString(string:) initializer
.
Final string's hash: 17891280220473
Yep, it's an NSString!
7.24 Find phone number in string
Problem
I want to detect a phone number within a given String.
Solution
Let’s set some example text.
let text = "This is an imaginary phone number: +34-1234567890"
Let’s create our detector.
We want the phone numbers, so we’ll look for:
NSTextCheckingResult.CheckingType.phoneNumber.rawValue.let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
let results = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
Loop through the phone numbers we found.
print(result.phoneNumber!)
How It Works
In order to find a phone number within some text, we may use the
NSDataDetector class
.
7.25 Find URL in string
Problem
I want to detect a URL in a given String.
Solution
Let’s set some example text.
let text = "The best site for Swift resources: https://iswift.org"
Let’s create our detector.
We want the URLs, so we’ll look for them in the following:
NSTextCheckingResult.CheckingType.link.rawValue.let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let results = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
Loop through the URLs we found.
How It Works
In order to find a URL within some text, we may use the NSDataDetector class.
https://iswift.org
7.26 Format number in string with leading zeros
Problem
I want to format a number contained in a String, adding leading zeros.
Solution
First, we set our number.
let a = 16
let b = 2
let c = 1986
Now, let’s format our numbers so that it has a fixed “size” of four digits and, if not, pad it with zeros.
let strA = String(format: "%04d", a)
let strB = String(format: "%04d", b)
let strC = String(format: "%04d", c)
And see what we’ve managed...
print("(a) => (strA)")
print("(b) => (strB)")
print("(c) => (strC)")
How It Works
To format a number as a string, with a number of leading zeros, we can use the
String(format:_) initializer
, along with the appropriate format.
16 => 0016
2 => 0002
1986 => 1986
7.27 Format number in string with specific decimal places
Problem
I want to format a number contained in a given String, specifying the number of decimal places.
Solution
First, we set our number.
Now, let’s format our number so that it has only two decimal places.
let str = String(format: "%.2f", num)
And see what we’ve managed...
How It Works
To format a number – float or double – as a string, with a specific number of decimal places, we can use the
String(format:_) initializer, along with the appropriate
format.
7.28 Format string by padding left with spaces
Problem
I want to format a given string by adding some left padding, with a number of spaces.
Solution
First, we set our string.
Now, let’s format our string so that it has a fixed “size” of 25, and – if not – pad it with spaces at the left.
let padded = String(repeating: " ", count: 25-str.count) + str
And print the
result.
print("Result: |(padded)|")
How It Works
To format a string with a number of spaces at the left, we can use the String’s
String(repeating:count:) initializer
, along with the necessary string manipulation.
7.29 Format string by padding right with spaces
Problem
I want to format a given string by adding some right padding, with a number of spaces.
Solution
First, we set our string.
Now, let’s format our string so that it has a fixed “size” of 25, and – if not – pad it with spaces at the
right.
let padded = str.padding(toLength: 25, withPad: " ", startingAt: 0)
And print the result.
print("Result: |(padded)|")
How It Works
To format a string with a number of spaces at the right, we can use the String’s
padding(toLength:withPad:startingAt:) method
.
7.30 Generate a unique identifier string
Problem
I want to generate a UUID string.
Solution
A single line does the trick.
let uuid = UUID().uuidString
How It Works
A UUID is a universally unique identifier, and there’s surely an easy way to generate one. How? By using Foundation’s
UUID class
.
9A4EE9F3-772D-4A17-A213-0828E9E7742A
7.31 Get character at index in string
Problem
I want to get the character at specific index of a given String.
Solution
Let’s initialize a test string.
We want the character at index: 6.
First, we get the index.
let index = str.index(str.startIndex, offsetBy: 6)
Then we retrieve the character.
Let’s see what we’ve managed...
print("Character at index 6: (char)")
How It Works
To get a particular character at a specific index of a
string, we’ll have to use the String’s
index(_,offsetBy:) method
and then subscript.
7.32 Get first X characters from string
Problem
I want to get the first characters from a given String.
Solution
First, we initialize a test
string.
let str = "Hello world!!!"
We want the string from the beginning of the string up to index: 5.
let indexFrom = str.startIndex
let indexTo = str.index(str.startIndex, offsetBy:5)
Then we retrieve the substring.
let substring = str[indexFrom..<indexTo]
How It Works
In order to get the first X characters of a string (the substring), we can use the subscript and the String’s
index(_,offsetBy:) method
.
7.33 Get index of character in string
Problem
I want to get the index of a specific character within a given String.
Solution
First, we initialize a test string.
Then, we get the index of ‘l’.
Careful: we have lots of ’l’s in the string. This way we’ll get the index of the first one.
let index = str.index(of: "l")
Index is an optional. Meaning: it’s not guaranteed that we’ll find the character. So, let’s first check if we did find the character.
// Now, let's convert the index to an Int
let intIndex : Int = str.distance(from: str.startIndex, to: index!)
print("First 'l' found at index: (intIndex)")
}
How It Works
To get the index of the first occurrence of a specific
character within a string, we can use
index(of:)
the method of its characters property.
First 'l' found at index: 2
7.34 Get index of substring in string
Problem
I want to get the index of a string within a given String.
Solution
First, we initialize a test string.
Then, we get the range of “world.”
let range = str.range(of: "world")
Range is an optional. Meaning: it’s not guaranteed that we’ll find the substring. So, let’s first check if we did find the
substring.
// First, let's get the initial index - or "lower bound" of the string's range
let index = range!.lowerBound
// Now, let's convert the index to an Int
let intIndex : Int = str.distance(from: str.startIndex, to: index)
print("String 'world' found at position: (intIndex)")
}
How It Works
To get the index of the first occurrence of a specific string within a string, we can use the
range(of:) method
.
String 'world' found at position: 6
7.35 Get last X characters from string
Problem
I want to get the last characters from a given String.
Solution
First, we initialize a test string.
let str = "Hello world!!!"
We want the string from index: 6 to the end of the string.
let indexFrom = str.index(str.startIndex, offsetBy:6)
let indexTo = str.endIndex
Then we retrieve the substring.
let substring = str[indexFrom..<indexTo]
How It Works
In order to get the last X characters of a string (the substring), we can use the subscript and the String’s
index(_,offsetBy:) method
.
7.36 Get length of string
Problem
I want to get the length of a given String.
Solution
So, let’s initialize some test string.
Let’s see...
print("Number of characters in the string: (length)")
How It Works
To get the length of the string, all we have to use String’s
count property
.
Number of characters in the string: 11
7.37 Get length of Unicode string
Problem
I want to get the length of a Unicode String.
Solution
So, to get the length of the string, we’d do as with a normal string: all we have to do is get the string’s characters and count them. Literally.
So, let’s initialize some test string.
That’s “Japanese.” In, well... Japanese.
Let’s see...
print("Number of characters in the string: (length)")
How It Works
In Swift, using
Unicode characters in string, works practically out of the box.
Number of characters in the string: 3
7.38 Get substring from string in range
Problem
I want to get a specific substring, from a specific range, within a given String.
Solution
First, we initialize a test string.
let str = "Hello world!!!"
We want the string from index: 6 to index: 11.
let indexFrom = str.index(str.startIndex, offsetBy:6)
let indexTo = str.index(str.startIndex, offsetBy:11)
Then we retrieve the substring.
let substring = str[indexFrom..<indexTo]
How It Works
In order to get a substring, from a string, given a specific range, we can use the subscript and for the different index the Strings
index(_,offsetBy:) method
.
7.39 Loop through characters in string
Problem
I want to iterate over the characters contained in a given String.
Solution
Let’s initialize our string with some value.
Iterate through the characters, with a for-in statement.
for char in str {
print(char)
}
How It Works
To get the characters in a string, we may just iterate over the
String itself using a for-in statement.
7.40 Repeat a string several times
Problem
I want to repeat a given String several times.
Solution
First, set an initial test string.
Now, let’s repeat it three times.
let repeated = String(repeating: str, count: 3)
Let’s see...
print("(str) => (repeated)")
How It Works
In order to repeat a string several times and create a new string, we can use the
String(repeating: count:) initializer
.
7.41 Check if string starts with string
Problem
I want to check if a String starts with another String.
Solution
First, we set some initial value.
We’re going to replace the first space.
if let subrange = str.range(of: "\s", options:.regularExpression) {
// Replace the substring with 'Hola'
str.replaceSubrange(subrange, with: "_")
print("Here is our new string: (str)")
}
How It Works
In order to replace a regex within a string, we can use the Strings
range(of:) method to first find its range, and then
replaceSubrange(_,with:)
in order to replace it.
Here is our new string: Hello_world
7.42 Replace substring in string by range
Problem
I want to replace a String within another String, given a specific range.
Solution
First, we set some initial value.
var str = "Hello World!!!"
We’ll want to replace everything from index: 6 up to index: 11.
let indexFrom = str.index(str.startIndex, offsetBy:6)
let indexTo = str.index(str.startIndex, offsetBy:11)
Time to replace it.
str.replaceSubrange(indexFrom..<indexTo, with: "Mundo")
And print it.
print("Here is our new string: (str)")
How It Works
In order to replace a substring within a string, given a specific
range, we can use the String’s
range(of:) method
to first find its range, and then
replaceSubrange(_,with:)
in order to replace it.
Here is our new string: Hello Mundo!!!
7.43 Replace substring in string
Problem
I want to replace a String within another String.
Solution
First, we set some initial value.
Now, let’s see...
if let subrange = str.range(of: "Hello") {
// Replace the substring with 'Hola'
str.replaceSubrange(subrange, with: "Hola")
print("Here is our new string: (str)")
}
How It Works
In order to replace a substring within a
string, we can use the String’s
range(of:) method
to first find its range, and then
replaceSubrange(_,with:)
in order to replace it.
Here is our new string: Hola World
7.44 Reverse a string
Problem
I want to reverse a String.
Solution
First, we set some initial value.
Time to reverse it.
let reversed = String(str.reversed())
Let’s see...
print("(str) => (reversed)")
How It Works
In order to reverse a string, we can use the String’s
reversed method
.
Hello World => dlroW olleH
7.45 Split string by lines
Problem
I want to split a given String into lines.
Solution
First, we set some initial value.
let str = "bananas
" +
"apples
" +
"apricots
" +
"pineapples
" +
"oranges"
Let’s split it by lines, and get the different types of fruit.
let lines = str.components(separatedBy: "
")
How It Works
In order to split a string by
lines, we can use the String’s
components(separatedBy:) method
.
["bananas", "apples", "apricots", "pineapples", "oranges"]
7.46 Split string by words
Problem
I want to split a given String by words.
Solution
First, let’s set some test string.
let str = "The quick brown fox jumps over the lazy dog"
Then, we set up our tagger – it can do LOTS more than just split our string to words, but let’s stick to that for now.
let options = NSLinguisticTagger.Options.omitWhitespace
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagScheme.lexicalClass],
options: Int(options.rawValue))
Time to loop through the tokens found.
var words : [String] = []
tagger.enumerateTags(in: NSMakeRange(0, (str as NSString).length), scheme: NSLinguisticTagScheme.lexicalClass, options: options) {
(tag, tokenRange, _, _) in
let token = (str as NSString).substring(with: tokenRange)
words.append(token)
}
How It Works
In order to split a string by words, the best way would be by using the
NSLinguisticTagger class
.
Words: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
7.47 Split string into array by separator
Problem
I want to split a given String into an array using a specific separator.
Solution
First, we set some initial value.
let str = "bananas,apples,apricots,pineapples,oranges"
Let’s split it by commas, and get the different types of fruit.
let fruit = str.components(separatedBy: ",")
How It Works
In order to split a string into an array, we can use the String’s components(separatedBy:) method
.
["bananas", "apples", "apricots", "pineapples", "oranges"]
7.48 Trim characters in string
Problem
I want to trim characters in a given String.
Solution
First, we set some initial value.
let str = "this is our string"
We want to “trim” all ‘t’s and ‘g’s.
let toTrim = CharacterSet(charactersIn: "tg")
let trimmed = str.trimmingCharacters(in: toTrim)
How It Works
In order to remove several
characters from the beginning and end of a string, we can use the String’s
trimmingCharacters(in:)
.
7.49 Trim whitespace in string
Problem
I want to trim all whitespace in a given String.
Solution
First, we set some initial value.
let str = " This is a string with some... space around "
Then, we convert it.
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
How It Works
In order to remove all
whitespace (and newlines) from the beginning and end of a string, we can use the String’s
trimmingCharacters(in:) method
.
: This is a string with some... space around :
7.50 Use string interpolation
Problem
I want to “include” an expression – string, number or whatever-that-may-be – within a String literal.
Solution
On the more... technical side, what string interpolation does is to embed the string representation (think of the description method) of a particular expression within another string.
Let’s set some initial variables.
let str = "hello"
let num = 6
let arr = [1,9,8,6] // yep, arrays too!
Now, let’s see it in action.
print("str = (str)")
print("num = (num)")
print("arr = (arr)")
This is not limited to
variables; you can actually use any expression.
print("str uppercased = (str.uppercased())")
print("num after addition = (num + 4)")
print("arr after sorting = (arr.sorted())")
How It Works
First, let’s set things straight: String interpolation is just a way to “include” an expression – string, number, whatever-that-may-be – within a string. That’s all. So, instead of concatenating string after string... you can just use the
(..) syntax
to just embed it.
str = hello
num = 6
arr = [1, 9, 8, 6]
str uppercased = HELLO
num after addition = 10
arr after sorting = [1, 6, 8, 9]
7.51 Use Unicode characters in string
Problem
I want to include Unicode characters in a String literal.
Solution
Let’s create some strings.
let a = "日本語 = Japanese"
let b = "You really u{2665} Swift, don't you?"
Let’s print them out.
print("a: (a)")
print("b: (b)")
How It Works
In Swift, using
Unicode characters in string works practically out of the box.
a: 日本語 = Japanese
b: You really ♥ Swift, don't you?
7.52 Summary
In this chapter, we’ve seen how to make the most out of our Strings in Swift.
In the next chapter, we’ll dig deeper and start exploring yet another one of the most fundamental objects in the Swift programming language: arrays and sets.