Capitalize first and last name Tag(s): String


Capitalization of a name is hard to do because they are many rules, see this Wikipedia article. Maybe that's one reason of why names are often printed with all uppercase letters!

However, we can cover many cases by using a simple rule like uppercase the first letter of each word separated by a space or a hyphen.

Using Java code

public class StringUtils {

  private StringUtils() {}

  public static void main(String[] args) {
    System.out.println(StringUtils.capitalize("john smith"));     // John Smith
    System.out.println(StringUtils.capitalize("john s. doe"));    // John S. Doe
    System.out.println(StringUtils.capitalize("john smith-doe")); // John Smith-Doe
  }

  public static String capitalize(String s) {
    if ((s == null) || (s.trim().length() == 0)) {
       return s;
    }
    s = s.toLowerCase();
    char[] cArr = s.trim().toCharArray();
    cArr[0] = Character.toUpperCase(cArr[0]);
    for (int i = 0; i < cArr.length; i++) {
       if (cArr[i] == ' ' && (i + 1) < cArr.length) {
         cArr[i + 1] = Character.toUpperCase(cArr[i + 1]);
       }
       if (cArr[i] == '-' && (i + 1) < cArr.length) {
         cArr[i + 1] = Character.toUpperCase(cArr[i + 1]);
       }
       if (cArr[i] == '\'' && (i + 1) < cArr.length) {
         cArr[i + 1] = Character.toUpperCase(cArr[i + 1]);
       }
    }
    return new String(cArr);
  }
}

Using Apache Commons
Apache Commons Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods. The WordUtils class is used to capitalize a serie of words.

import org.apache.commons.lang.WordUtils;

public class Test3 {
  public static void main(String[] args) {
    System.out.println(WordUtils.capitalize("john smith")); // John Smith
    System.out.println(WordUtils.capitalize("john smith-doe")); // John Smith-doe
    System.out.println(WordUtils.capitalizeFully("john smith-doe", new char[] { ' ', '-' })); // John Smith-Doe
  }
}
Maven POM for Apache Commons Lang
 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
 </dependency>

Using Oracle
If a database connection is available then a quick Oracle request with the INITCAP function will return a capitalized string.

SELECT initcap('john smith-doe') FROM dual
will return John Smith-Doe.
blog comments powered by Disqus