Problem overview
The function capitalizeWords takes a string sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence neither starts nor ends with a space. Only the first character of a word changes. The rest of the word stays exactly as it is, even when it already has upper-case letters, and a first character that has no upper case, such as a digit, stays too.
"hello world" becomes "Hello World". "learn to code with AlgoCademy" becomes "Learn To Code With AlgoCademy": AlgoCademy already starts with a capital. "iPhone and NASA" becomes "IPhone And NASA", because only the first character of each word is touched.
Approach
Break the sentence into words, fix each word on its own, and glue the words back together. This is a common shape for text problems: split, transform each piece, join.
To fix one word, cut it into its first character and the rest. The first character is converted to upper case, and the rest is appended without any change. Leaving the rest alone is what keeps NASA from turning into Nasa.
Step by step
- Split the sentence at the spaces with
sentence.split(" ")and store the result inval words. For"hello world"that is the two wordshelloandworld. - Create
val resultas an emptyArrayBuffer[String], written with its full package path,scala.collection.mutable.ArrayBuffer. It is avalbecause the buffer itself isn't replaced, only grown. - Write a
forloop with a variablewordoverwords. - Inside, build
capitalized: the first character,word.substring(0, 1), converted withtoUpperCase, followed byword.substring(1), everything after it. - Append
capitalizedtoresultwith+=. - After the loop, return
result.mkString(" "). It joins the buffer's strings with a single space between each two.
For "iPhone and NASA" the words are iPhone, and and NASA. They become IPhone, And and NASA, and the joined result is IPhone And NASA.
The solution in Scala
class Solution {
def capitalizeWords(sentence: String): String = {
val words = sentence.split(" ")
val result = scala.collection.mutable.ArrayBuffer[String]()
for (word <- words) {
val capitalized = word.substring(0, 1).toUpperCase + word.substring(1)
result += capitalized
}
return result.mkString(" ")
}
}
Details that matter in Scala:
substring(0, 1)takes the characters from index 0 up to, but not including, index 1: one character.substring(1)takes everything from index 1 to the end. For a one-letter word, such asa,substring(1)is an empty string, so the code works without a special case.toUpperCasereturns a new string. Strings are immutable, so the original word isn't changed. A digit stays as it is:"3d".substring(0, 1).toUpperCaseis"3".split(" ")returns anArray[String], andfor (word <- words)visits its elements in order.mkString(" ")takes the separator. It puts it between the elements only, so there is no trailing space. For example,Array("a", "b").mkString("[", "|", "]")gives[a|b].- A
valholding anArrayBuffercan still grow:valstops you from reassigningresult, not from adding to the buffer.
Edge cases and common mistakes
- Upper-casing the whole word. Calling
toUpperCaseon the wholewordturnsAlgoCademyintoALGOCADEMY. Only the first character should change. - Lower-casing the rest. That would turn
NASAintoNasa, which the task doesn't ask for. - A word that starts with a digit.
3d printingbecomes3d Printing. - Extra spaces. The lesson promises single spaces. If a sentence had two in a row,
split(" ")would produce an empty word in between:"hello world".split(" ")giveshello, an empty string andworld.
Testing
capitalizeWords("hello world") -> Hello World
capitalizeWords("learn to code with AlgoCademy") -> Learn To Code With AlgoCademy
capitalizeWords("iPhone and NASA") -> IPhone And NASA
capitalizeWords("a b") -> A B
capitalizeWords("3d printing") -> 3d Printing
