Problem overview
The function capitalizeWords receives a sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest stays exactly as it is, even if it has capital letters. A first character with no upper case, such as a digit, stays too.
"hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": "Phone" and "ASA" keep their letters as they were. "3d printing" becomes "3d Printing".
Approach
Break the sentence into words, fix the first character of each word, and glue the words back together with spaces. That gives three small jobs, each of which has a standard Swift tool: split to cut, prefix and dropFirst to take a word apart, and joined to put the pieces together.
Because the words are separated by single spaces, splitting at a space and joining with a space puts every space back where it was.
Step by step
- Split the sentence.
sentence.split(separator: " ")returns the words. Each piece is aSubstring, a view into the original string, and the whole result is anArray<Substring>. - Create
var result = [String](), an empty array of strings. It grows inside the loop, so it is avar. - Loop over the words with
for word in words. - Build the capitalized word.
word.prefix(1)is the first character,.uppercased()turns it into an upper-caseString, andString(word.dropFirst())is everything after it, converted from aSubstringto aString. Adding the two strings gives the new word. A one-letter word works too:dropFirst()of it is empty. - Append it to
result. - Join and return.
result.joined(separator: " ")glues the strings together with a space between each two.
The solution in Swift
class Solution {
func capitalizeWords(_ sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = [String]()
for word in words {
let capitalized = word.prefix(1).uppercased() + String(word.dropFirst())
result.append(capitalized)
}
return result.joined(separator: " ")
}
}
Swift details worth knowing:
- Substring versus String.
splitgivesSubstringvalues.prefix(1).uppercased()already returns aString, butword.dropFirst()is still aSubstring, and+needs two values of the same type. Wrapping it inString(...)fixes that. prefix(1)is safe. It takes at most one character and doesn't fail on an empty string. Indexing withword[0]isn't possible: Swift strings can't be indexed with anInt.uppercased()on a digit. Upper-casing"3"returns"3", so words starting with a digit need no special case.splitdrops empty pieces. By default it leaves out empty subsequences. With the lesson's single spaces that makes no difference, but it means doubled spaces would collapse into one when joined back.letandvar.wordsandcapitalizednever change, so they arelet.resultgrows, so it isvar.
Edge cases and common mistakes
- One word.
"hello"gives"Hello", and the join adds no space. - One-letter words.
"a b"gives"A B". - Apostrophes.
"it's ok"gives"It's Ok". Only the first character of"it's"changes. - Existing capitals.
"learn to code with AlgoCademy"gives"Learn To Code With AlgoCademy". Lower-casing the rest of each word would damage"NASA", which the lesson says to leave alone. - Forgetting the
String(...)conversion. Adding aStringand aSubstringdoesn't compile.
Testing
"hello world"gives"Hello World"."learn to code with AlgoCademy"gives"Learn To Code With AlgoCademy"."iPhone and NASA"gives"IPhone And NASA"."3d printing"gives"3d Printing"."it's ok"gives"It's Ok".
