Tuesday 28 June 2011

Capitalise First Letters of String (Useful for Name Conversion)

There are several java utils which can walkthrough words and turn first characters to upper cases - yet if you're like me looking to implement something pretty simple but powerful and also can be easily customized in various ways, then DIY sounds like the way forward.

Below example is something more simple for beginners to start with.

public final class MyUtils
{
  /**
   * Capitalize the First characters of passed Name. If the Name passed are separated by whitespaces, dots, hyphen or apostrophe, the first
   * characters will be capitalized. Example:
   * 

* The name passed = bright dadson.code-nathan o'brian, NameCapitalize(..) will change it to Bright Dadson.Code-Nathan O'Brian *

* @param string * @return */ public static String mameCapitalize(String string) { if (!(string == null)) { char[] replacer = string.toCharArray(); for (int i = 0; i < replacer.length; ++i) { if (((i > -1) && (i == 0)) && Character.isLetter(string.charAt(i))) replacer[i] = Character.toUpperCase(string.charAt(i)); else if ((Character.isWhitespace(string.charAt(i))) || (string.charAt(i) == '-') || (string.charAt(i) == '.' || (string.charAt(i) == '\''))) { if ((i == (replacer.length - 1)) && !Character.isLetter(string.charAt((replacer.length - 1)))) break; if (!(Character.isUpperCase(replacer[(i + 1)]))) { replacer[(i + 1)] = Character.toUpperCase(replacer[(i + 1)]); } } } return String.copyValueOf((replacer)); } return null; } /**To use the util capitalize - something like this**/ public static void main(String... args) { System.out.println(MyUtil.NameCapitalize("bright dadson.code-nathan o'brian")); } }
You are simply creating a pointer in the memory locations to which you modify the address values to upper cases.