It's been a while since I posted the last article. Today's is a nice and simple one for rehab.
This series of articles follows Stephen Grider's Udemy course in three different languages. JavaScript solutions are by Stephen. I try to "translate" them into Python and Java.
Today's question is:
--- Directions
Write a function that accepts a string. The function should
capitalize the first letter of each word in the string then
return the capitalized string.
--- Examples
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
1: Concise solution using built-in libraries
JavaScript:
function capitalize(sentence) {
const words = [];
for (let word of sentence.split(' ')) {
words.push(word[0].toUpperCase() + word.slice(1));
}
return words.join(' ');
}
Python:
def capitalize1(sentence: str) -> str:
words = [word[0].upper() + word[1:] for word in sentence.split()]
return ' '.join(words)
def capitalize2(sentence: str) -> str:
return ' '.join([word.capitalize() for word in sentence.split()])
def capitalize3(sentence: str) -> str:
return sentence.title()
Java:
import java.util.LinkedList;
import java.util.List;
public static String capitalize(String sentence) {
List<String> words = new LinkedList<>();
for (String word : sentence.split(" ")) {
words.add(String.valueOf(word.charAt(0)).toUpperCase() + word.substring(1));
}
return String.join(" ", words);
}
2: Brute force solution using a loop
JavaScript:
function capitalize(sentence) {
let result = sentence[0].toUpperCase();
for (let i = 1; i < sentence.length; i++) {
if (sentence[i - 1] === ' ') {
result += sentence[i].toUpperCase();
} else {
result += sentence[i];
}
}
return result;
}
Python:
def capitalize(sentence: str) -> str:
result = ''
for i, char in enumerate(sentence):
if i == 0 or sentence[i - 1] == ' ':
result += char.upper()
else:
result += char
return result
Java:
public static String capitalize(String sentence) {
StringBuilder result = new StringBuilder(String.valueOf(sentence.charAt(0)).toUpperCase());
for (int i = 1; i < sentence.length(); i++) {
if (sentence.charAt(i - 1) == ' ') {
result.append(String.valueOf(sentence.charAt(i)).toUpperCase());
} else {
result.append(sentence.charAt(i));
}
}
return result.toString();
}
Thank you for reading so far. I hope to see you again soon!
Top comments (3)
Javascript code can be simplier
sentence.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
Thank you. This is nice!
A Java equivalent would be:
I tried it in Python, too:
though I find this far less understandable than my original solutions using list comprehensions.
Nice!