Monday, March 5, 2012

How do I capitalize each word in a string in android?


This examples show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-lang. We can use the WordUtils.capitalize(str) orWordUtils.capitalizeFully(str).

import org.apache.commons.lang.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        //
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        //
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        //
        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        //
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

Below is the output...

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

1 comment:

  1. By default WordUtils is not provided in Android. But you can find the implementation of it here:

    https://code.google.com/p/android-delayed/source/browse/src/org/apache/commons/lang/WordUtils.java?r=93d2d09af8f3711433bc20aa9587372782e38352&spec=svnb6361674e474f44cd70fed634c9ee7dd60245867

    ReplyDelete