We can get the length of a string using the .count property like this:
var message = "Hello world"
// Printing the length:
print(message.count) // Output: 11
// Changing the message:
message += "!"
// Printing the new length:
print(message.count) // Output: 12
Accessing characters from the end:
The length is useful for accessing characters from the end of a string.
Because strings are 0-indexed, the index of the last character is length - 1:
var message = "Hello world"
let length = message.count
// Printing the last character:
let lastIdx = message.index(message.endIndex, offsetBy: -1)
print(message[lastIdx]) // Output: d
// Printing the second to last character:
let secondLastIdx = message.index(message.endIndex, offsetBy: -2)
print(message[secondLastIdx]) // Output: l
In general, if you want the nth last character, you use message[message.index(message.endIndex, offsetBy: -n)].
Slicing characters from the end:
The length is also useful for slicing some characters from the end of a string:
var message = "Hello world"
let length = message.count
// Slicing last 4 characters:
var lastChars = String(message.suffix(4))
print(lastChars) // Output: orld
// Slicing last 7 characters:
lastChars = String(message.suffix(7))
print(lastChars) // Output: o world
In general, if you want the last n characters, you use String(message.suffix(n)).
Assignment
Follow the Coding Tutorial and let's practice with string length!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.