A string as an array of characters
A String will not hand over the character at a position, so you make an array of its characters once and work on that.
- Reach for it when
- The input is a
Stringand you need the character at a position. - The move
- Swift won't take
s[3]. Writelet chars = Array(s)once, work on the array, and finish withString(chars). - Cost
Array(s)is one pass, done once.
The idea
A librarian turned me away yesterday. All I asked for was the fourth book on the shelf.
That is more or less the whole job.
You'd think. We'll come back to her. Here's a word: swift. What's its fourth letter?
F.
Now ask Swift. Put the word in s and write s[3].
It won't compile. The compiler says it cannot subscript a String with an Int.
An array would hand over numbers[3] without a murmur. What's so special about a string?
Its characters don't all take the same room: an a takes 1 byte and a flag takes 8. So Swift can't work out where the fourth one starts, and has to walk there from the front, past the first three.
So a string is a shelf of books, thin ones and fat ones. Nobody knows where the fourth book starts until a finger has run along three spines.
And an array is a row of boxes, all the same width, numbered from 0. Box 3 is three widths along. Nobody walks.
Swift could do the walk for me and keep quiet about it.
Then s[3] in a loop would be a walk on every pass, and each one would look like a single step. Swift would rather say no than let a walk pass for a step.
So I walk the shelf every time I want a book?
You walk it once. let chars = Array(s) goes along the shelf one time and puts each book in a box. After that chars[3] is one step, as often as you like.
And when the problem wants a string back, not a row of boxes?
String(chars). The books go back on a shelf.
Boxes for the work, and a shelf to hand it in on. Somebody should tell that librarian.
I suspect she knows. It's her shelf.
That is the whole tool: make an array of the characters once, do the work on the array, and turn it back into a string at the end. A string also does a few things well as it is, and this lesson has those too, each with its trap.
The shape
Write let fourth = s[3] and this is all the compiler has to say:
error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
What you write instead has three lines, and you know them by heart. Here they change one character of a string:
/// `s` with the character at position `i` changed to `replacement`.
func replaced(_ s: String, at i: Int, with replacement: Character) -> String {
var chars = Array(s) // once: every character gets a numbered box
chars[i] = replacement // the work: on the array, by position
return String(chars) // the finish: the characters become a string again
}It has three parts, and each is there for a reason.
- Once.
Array(s)walks the shelf one time and puts every character in a numbered box. The number is the character's position. It is avarhere because the work changes a box. When the work only reads, it is alet. - The work. It is done on the array.
chars[i]reads boxi,chars[i] = …changes it, andchars.countsays how many boxes there are. Each is one step. - The finish.
String(chars)puts the characters back on a shelf, because the problem asked for aString. When the answer is a number or a yes or no, there is nothing to put back, and this line goes.
Array(s) is not magic. It is this loop, done for you:
/// What `Array(s)` does: one walk along the string, each character into the next box.
func arrayOfCharacters(_ s: String) -> [Character] {
var chars: [Character] = []
for character in s {
chars.append(character)
}
return chars
}One walk, however long the string. So it is written once, above the work, and never inside a loop.
Watch it run
The call is replaced("swift", at: 1, with: "h"). Its first line is the walk. Here is each character going into its box.
| character | its box | chars after |
|---|---|---|
| s | 0 | ["s"] |
| w | 1 | ["s", "w"] |
| i | 2 | ["s", "w", "i"] |
| f | 3 | ["s", "w", "i", "f"] |
| t | 4 | ["s", "w", "i", "f", "t"] |
Then the work: chars[1] = "h" leaves chars as ["s", "h", "i", "f", "t"]. Then the finish: String(chars) is shift.
Look at the fourth row. The fourth character went into box 3, because the boxes are numbered from 0. So the last of five is in box 4, and there is no box 5.
Step by step
The number of characters in a string
The first two steps are things a string does well as it is. The boxes come back in step 3. This step comes in two small parts.
First, count by walking.
/// How many characters `s` holds, counted by walking it.
func numberOfCharacters(_ s: String) -> Int {
var count = 0
for _ in s { // one pass for each character
count += 1
}
return count
}What is new: a string can be walked. The for loop you know takes its characters one at a time, in order. It is the loop inside Array(s) with the boxes left out. This one never looks at the character it is on, so the character is named _. For swift it gives 5.
A character is what a reader would call one. café is 4 characters in 5 bytes, and a flag is 1 character in 8. The walk counts characters, never bytes.
Then, let Swift walk, once.
/// How many of `limits` the string fits within. A limit is the most characters allowed.
func limitsMet(_ s: String, _ limits: [Int]) -> Int {
let length = s.count // asked once: one walk
var met = 0
for limit in limits {
if length <= limit { // exactly at the limit still fits
met += 1
}
}
return met
}What is new: s.count. It is the loop above, built in: the same number, by the same walk. A string does not keep its count, so the shelf is walked from end to end every time you ask. So length asks once, above the loop, and the loop uses the answer.
For swift and the limits 3, 5 and 8 this gives 2: five characters fit within 5 and within 8. With s.count <= limit inside the loop the answer would be the same, after a walk for every limit. The problem for this part has a clock on it, to tell the two apart.
The first and the last character, and what an empty string gives
The two ends of a shelf are always within reach. s.first and s.last are one step each, with no walk and no boxes.
/// The first and the last character of `s`, in that order.
/// An empty string gives an empty array.
func firstAndLast(_ s: String) -> [Character] {
if let first = s.first, let last = s.last {
return [first, last]
}
return [] // an empty string has neither
}What is new: first and last hand back optionals. An empty string has no first character, so Swift cannot promise one, and gives nil. You open the optional as you would in an app, with if let.
For swift this gives ["s", "t"]. A string of one character has that character at both ends, so "a" gives ["a", "a"]. An empty string gives [].
The trap is to compare the two without opening them. For an empty string, s.first == s.last is true, because nil equals nil. When the question is whether the ends match, open them first:
/// Whether `s` starts and ends with the same character. An empty string does not.
func endsMatch(_ s: String) -> Bool {
if let first = s.first, let last = s.last {
return first == last
}
return false // no ends, so nothing to match
}For level this gives true, for swift false, and for an empty string false. This step's second problem hands you the unopened comparison to mend.
The character at position i, by way of Array(s)
This step is the shape, and it comes in three small parts.
First, read a box.
/// The character at position `i` of `s`. Positions start at 0.
func character(_ s: String, at i: Int) -> Character {
let chars = Array(s) // every character gets a position
return chars[i] // so this is an ordinary array read
}What is new: Array(s). It gives every character a position, and after it chars[i] is an ordinary array read. For swift and position 3 this gives f: the fourth character, because positions start at 0. The problems promise that i is a position in the string, so the box is always there.
Then, change a box. This is replaced, the shape at the top of the lesson. What is new is its last line: String(chars) turns an array of characters back into a string. For swift, position 1 and "h" it gives shift.
That "h" looks like a string and is a Character. Swift reads one quoted letter as a String unless the place it goes asks for a Character.
Last, one walk for many boxes.
/// The characters of `s` at each of `positions`, in the order they are asked for.
func characters(_ s: String, at positions: [Int]) -> [Character] {
let chars = Array(s) // once, above the loop
var found: [Character] = []
for i in positions {
found.append(chars[i]) // one step each, however many are asked for
}
return found
}What is new: where the first line goes. Array(s) is above the loop, so the string is walked once, however many positions are asked for. For swift and the positions 4, 0 and 4 this gives ["t", "s", "t"]. Inside the loop, the same line would walk the whole string again for every position. The problem for this part has a clock on it too.
Build a new string one character at a time
/// `s` with its spaces taken out.
func withoutSpaces(_ s: String) -> String {
var kept = "" // an empty string to build on
for character in s {
if character != " " {
kept.append(character) // one more character on the end
}
}
return kept
}What is new: a string that starts empty and grows at its end. var kept = "" is an empty shelf, and kept.append(character) puts one more book on the end of it. For by heart this gives byheart.
append is the word to know. kept += character does not compile, because += wants a string on its right and a character is not one.
Reverse a string
/// `s` with its characters in the opposite order.
func reversed(_ s: String) -> String {
let chars = Array(s)
var backwards = ""
for i in chars.indices.reversed() { // from the last box to the first
backwards.append(chars[i])
}
return backwards
}What is new: the order is yours. A string hands over its characters front to back. Boxes can be visited in any order, and here it is from the last to the first, the backwards walk of "Loops and indexes". For swift this gives tfiws.
Swift can do the whole job in one line:
func reversedShort(_ s: String) -> String {
return String(s.reversed())
}s.reversed() hands over the characters last one first, and String(…) makes a string of them. Both ways are right. Learn the loop: it is the one you can change when a problem wants something other than a plain reverse.
Is a string the same forwards and backwards?
A string that reads the same both ways, like level, is called a palindrome.
/// Whether `s` reads the same forwards and backwards.
func isPalindrome(_ s: String) -> Bool {
return s == reversed(s) // the same characters in the same order
}What is new: == compares two strings whole. They are equal when they hold the same characters in the same order. So this is a question you can already answer: reverse the string, and see whether you got it back. For level this gives true. For swift it gives false, because tfiws is not swift.
A string of one character is a palindrome, and so is an empty string: neither has anything in it that could differ.
In this step's problem there is no reversed to call, so the answer has step 5's loop in it and ends with return s == backwards.
This builds a second string as long as the first. There is a way that builds nothing, with a position at each end, and it is the lesson "Two ends moving inward".
Count the vowels
/// How many of the characters of `s` are vowels.
func numberOfVowels(_ s: String) -> Int {
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
var count = 0
for character in s {
if vowels.contains(character) {
count += 1
}
}
return count
}What is new: a set. vowels holds the five characters, and vowels.contains(character) says whether this one is among them, in one step. Everything else is step 1's loop with an if in it. For swift this gives 1. For queue it gives 4: the set holds each vowel once, and the string may use it as often as it likes. For rhythm it gives 0.
The type has to be written out. Without : Set<Character>, Swift takes the five for strings, and vowels.contains(character) does not compile. The lesson "A set" has the rest of what a set does.
What goes wrong
A walk on every pass. Three things walk the string: Array(s), s.count, and the String.Index that the compiler's message offers, which is the walk written out by you: s[s.index(s.startIndex, offsetBy: i)]. Each is right, and each is fine once. In a loop over a string of 1,000 characters, this is how many characters each one walks past:
| written in the loop | characters walked past |
|---|---|
s[s.index(s.startIndex, offsetBy: i)] | 499,500 |
Array(s)[i] | 1,000,000 |
while i < s.count | 1,001,000 |
chars[i], with Array(s) once above the loop | 1,000 |
for i in 0..<s.count asks for the count once, and is fine. while i < s.count asks before every pass. chars.count is one step, because an array keeps its count. And to ask only whether a string holds anything, s.isEmpty does not walk at all.
Opening first or last by force. For an empty string s.first is nil, so s.first! stops the program. Use if let, and remember that two nils are equal.
An empty string. Array("") has no boxes, so chars[0] stops the program. The loops in this lesson need no special case, because a loop over nothing does nothing: an empty string has 0 characters and 0 vowels, and reversed it is still empty. Before you index, though, decide what an empty string should give.
One box too far. The last box is chars.count - 1. For swift that is box 4, and chars[5] stops the program.
A character where a string is wanted. Leave the type off vowels, or write kept += character, and the compiler says the same thing both times: cannot convert value of type 'Character' to expected argument type 'String'. Write Set<Character>, and use append.
Say it back
Why will Swift not take s[3]?
Show the answerHide the answer
Characters do not all take the same room, so the fourth can only be found by walking past the first three. Swift will not let that walk look like one step.
What do you write instead, and how often?
Show the answerHide the answer
let chars = Array(s), once, above the loop. After that chars[3] is one step, as often as you ask.
The answer has to be a String. How does the array become one?
Show the answerHide the answer
String(chars), as the last line.
What do s.first and s.last hand back, and why?
Show the answerHide the answer
Optionals, because an empty string has neither. Open them with if let before you compare them: nil equals nil.
s.count and chars.count give the same number. What is the difference?
Show the answerHide the answer
s.count walks the whole string every time it is asked. chars.count is one step.
How do you put one more character on the end of a string you are building?
Show the answerHide the answer
kept.append(character). += wants a string, and a character is not one.
Why did the librarian turn Harper away?
Show the answerHide the answer
Her shelf is a String. Its books are not all the same width, so the fourth is found only by walking past three, and she will not pass a walk off as a step. Harper should have put the books in boxes first, with Array(s), and asked for box 3.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | How many characters? | Easy |
| 2 | Ask for the count once | Easy |
| 3 | The first and the last character | Easy |
| 4 | Do the two ends match? | Easy |
| 5 | The character at a position | Easy |
| 6 | Change one character | Easy |
| 7 | One walk, many positions | Easy |
| 8 | Without the spaces | Easy |
| 9 | Reverse a string | Easy |
| 10 | The same forwards and backwards? | Easy |
| 11 | Count the vowels | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.