Coding problem · Easy · Basics
Capitalize Each Word
Easy Algorithms & data structures
Given a sentence s of lower-case words separated by single spaces, return it with the first letter of each word in upper case.
Example 1
Input: s = "hello world" Output: "Hello World"
Example 2
Input: s = "ready camel learns fast" Output: "Ready Camel Learns Fast"
Hints
Hint 1
Split the sentence into words.
Hint 2
Upper-case the first character of each word, keep the rest, then join with spaces.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(n)
Split on spaces, transform each word (word[0].toUpperCase() + word.slice(1)), and join the words back together.
Reference solution
function capitalizeWords(s) {
return s.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
}
function capitalizeWords(s: string): string {
return s.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
}
def capitalize_words(s: str) -> str:
return ' '.join(w[:1].upper() + w[1:] for w in s.split(' '))
<?php
function capitalizeWords(string $s): string
{
return implode(' ', array_map(fn ($w) => ucfirst($w), explode(' ', $s)));
}
class Solution {
public String capitalizeWords(String s) {
String[] words = s.split(" ");
for (int i = 0; i < words.length; i++) {
if (!words[i].isEmpty()) words[i] = Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1);
}
return String.join(" ", words);
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy
- Make an Acronym · Easy