Capitalize words in sentence

This example will show how to capitalize every word in a sentence using java and apache commons. Similar to capitalizing the first letter in a sentence we will use another phrase from the famous Super why! theme song.

Straight up Java

This snippet will show how to capitalize the first char of each word in a sentence using core java. Assuming that your phrase is separated by a space, this will split the sentence into an array and capitalize the first letter of the word. There is definitely gaps in this approach as you will need to handle multiple spaces between words and removing the space at the end.

Capitalize each word

@Test
public void capitalize_each_word_in_sentence_java () {

    String superWhyexample = "Come along With the Super Readers.";

    String[] exampleSplit = superWhyexample.split(" ");

    StringBuffer sb = new StringBuffer();
    for (String word : exampleSplit) {
        sb.append(word.substring(0, 1).toUpperCase() + word.substring(1));
        sb.append(" ");
    }
    assertEquals("Come Along With The Super Readers. ", sb.toString());
} 

Capitalize each word w/ breakiterator

This snippet will capitalize the first letter of each word using BreakIterator. This feels a bit complicated and more code but it does have the opportunity to handle specific use cases. The BreakIterator implements methods to find the location and boundaries of text maintaining the current position. The first method below will loop through each position of the sentence and call the nextWordStartAfter. The nextWordStartAfter will find the next word in the sentence while checking if there is any other words to process. The main method will then upper case the first letter of the word.

@Test
public void capitalize_each_word_in_sentence_java_with_BreakIterator () {

    String nineTeenEightyFourQuote = "It was a bright cold day in April, "
            + "and the clocks were striking thirteen.";

    StringBuffer wordCapitalSentence = new StringBuffer();
    int startPosition = 0, nextWordPosition = 0;
    String word = null;
    while (startPosition < nineTeenEightyFourQuote.length()) {

        nextWordPosition = nextWordStartAfter(startPosition, nineTeenEightyFourQuote);

        // check to see if there is a next word
        if (nextWordPosition == BreakIterator.DONE) {
            nextWordPosition = nineTeenEightyFourQuote.length();
        }

        // get the next word
        word = nineTeenEightyFourQuote.substring(startPosition, nextWordPosition);

        // upper case first letter of word
        wordCapitalSentence.append(word.substring(0, 1).toUpperCase() + word.substring(1));

        // set start to the next word position
        startPosition = nextWordPosition;
    }

    assertEquals("It Was A Bright Cold Day In April, And The Clocks Were Striking Thirteen.",
            wordCapitalSentence.toString());
}

private static int nextWordStartAfter(int pos, String text) {
     BreakIterator wb = BreakIterator.getWordInstance();
     wb.setText(text);
     int last = wb.following(pos);
     int current = wb.next();
     while (current != BreakIterator.DONE) {
         for (int p = last; p < current; p++) {
             if (Character.isLetter(text.codePointAt(p)))
                 return last;
         }
         last = current;
         current = wb.next();
     }
     return BreakIterator.DONE;
 }   

Apache Commons

The WordUtils.capitalizeFully method in apache commons will convert all the whitespace separated words in a String into capitalized words.

Capitalize each word

@Test
public void capitalize_each_word_in_sentence_apache_commons () {

    String prideAndPrejudiceSentence = "It is a truth universally acknowledged, "
            + "that a single man in possession of a good fortune, must be in want of a wife.";

    String eachWordCapitalized = WordUtils.capitalizeFully(prideAndPrejudiceSentence);

    assertEquals("It Is A Truth Universally Acknowledged, That A Single "
            + "Man In Possession Of A Good Fortune, Must Be In Want Of A Wife.",
            eachWordCapitalized);
}