DEV Community

tommy-3
tommy-3

Posted on • Updated on

Learning Algorithms with JS, Python and Java 8: Sentence Capitalization

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(' ');
}
Enter fullscreen mode Exit fullscreen mode

Python:

def capitalize1(sentence: str) -> str:
    words = [word[0].upper() + word[1:] for word in sentence.split()]
    return ' '.join(words)
Enter fullscreen mode Exit fullscreen mode
def capitalize2(sentence: str) -> str:
    return ' '.join([word.capitalize() for word in sentence.split()])
Enter fullscreen mode Exit fullscreen mode
def capitalize3(sentence: str) -> str:
    return sentence.title()
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading so far. I hope to see you again soon!

Top comments (3)

Collapse
 
emptyhand profile image
Emptyhand

Javascript code can be simplier

sentence.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');

Collapse
 
tommy3 profile image
tommy-3

Thank you. This is nice!

A Java equivalent would be:

import java.util.stream.Collectors;
import java.util.stream.Stream;

public static String capitalize(String sentence) {
    return Stream.of(sentence.split(" "))
            .map(word -> String.valueOf(word.charAt(0)).toUpperCase() + word.substring(1))
            .collect(Collectors.joining(" "));
}
Enter fullscreen mode Exit fullscreen mode

I tried it in Python, too:

def capitalize(sentence: str) -> str:
    return ' '.join(map(lambda word: word[0].upper() + word[1:], sentence.split()))
Enter fullscreen mode Exit fullscreen mode

though I find this far less understandable than my original solutions using list comprehensions.

Collapse
 
afuenzalida profile image
Andrés Fuenzalida

Nice!