Problem overview
The method capitalizeWords receives a sentence and returns it with the first character of every word in upper case. Words are separated by single spaces, and the sentence has no space at the start or end. Only the first character of each word changes. The rest of the word stays as it is, even when it contains upper-case letters, and a first character that has no upper case, such as a digit, stays too.
"hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": the Phone in iPhone and the ASA in NASA are untouched.
Approach: split, fix each word, join
Break the sentence into words, capitalize the first character of each, then put the words back with the same spaces. Splitting at single spaces and joining with single spaces restores every space exactly where it was.
Step by step
- Split the sentence with
sentence.split(" ")into aString[]namedwords. - Create an empty
List<String>namedresult, a newArrayList, to collect the fixed words in order. - Loop over
wordswith an enhancedforloop and aStringvariableword. - Build the capitalized word:
word.substring(0, 1)is the first character,toUpperCase()converts it, andword.substring(1)is everything after it. - Add the new word to
result. - Join the words with
String.join(" ", result)and return the text.
The solution in Java
class Solution {
public String capitalizeWords(String sentence) {
String[] words = sentence.split(" ");
List<String> result = new ArrayList<>();
for (String word : words) {
String capitalized = word.substring(0, 1).toUpperCase() + word.substring(1);
result.add(capitalized);
}
return String.join(" ", result);
}
}
Running it gives these results:
| Input | Output |
|---|---|
"hello world" | "Hello World" |
"learn to code with AlgoCademy" | "Learn To Code With AlgoCademy" |
"iPhone and NASA" | "IPhone And NASA" |
"5th avenue" | "5th Avenue" |
Java details:
- Strings are immutable. Methods such as
toUpperCaseandsubstringreturn new strings and never change the original, which is why the method builds a new list instead of editingwords. substring(start)versussubstring(start, end). The end index is exclusive, sosubstring(0, 1)is the first character only.substring(1)runs to the end of the string.- One-letter words. For
"a",substring(1)is the empty string. It is legal because the start index equals the length. Indexes beyond the length throw an exception. - Digits.
toUpperCaseon"5"gives"5", so a word like5thkeeps its first character. String.jointakes a separator and any collection of strings, so it works on theList<String>directly.
Another way to upper-case the first letter
The first character can also be handled as a char: Character.toUpperCase(word.charAt(0)) + word.substring(1) gives IPhone for iPhone. Here charAt(0) returns a char, and adding a String to it afterwards works because the + with a String on one side does string concatenation. Beware of adding two char values, which adds their numeric codes. The substring(0, 1) form used in the lesson stays a String throughout, which avoids that trap.
Edge cases and common mistakes
- Lower-casing the rest. Calling
toLowerCase()onword.substring(1)would turnNASAintoNasa. The task keeps it asNASA. - A double space. The task promises single spaces. If a sentence had two in a row,
split(" ")would produce an empty string between them, andsubstring(0, 1)on it would throw aStringIndexOutOfBoundsException. - A single word.
"hello".split(" ")gives an array with one element, so the method works for it unchanged. - Capitalizing only the first word. The loop has to run over every element of
words.
Testing
"hello world"gives"Hello World"."a b"gives"A B"."iPhone and NASA"gives"IPhone And NASA"."5th avenue"gives"5th Avenue".
