Format string to camel case - Android java.lang

Android examples for java.lang:String Case

Description

Format string to camel case

Demo Code

public class Main {
    public static final char[] WORD_SEPARATORS = { '_', '-', '@', '$', '#',
            ' ' };

  public static boolean isWordSeparator(char c) {
    for (int i = 0; i < WORD_SEPARATORS.length; i++) {
      if (WORD_SEPARATORS[i] == c) {
        return true;
      }//from  ww  w  .j  a va  2  s .  c  o m
    }
    return false;
  }

  /**
   * <pre>
   * StringUtil.camelString("ITEM_CODE", true)  = "ItemCode"
   * StringUtil.camelString("ITEM_CODE", false) = "itemCode"
   * </pre>
   * 
   */
  public static String camelString(String str, boolean firstCharacterUppercase) {
    if (str == null) {
      return null;
    }

    StringBuffer sb = new StringBuffer();

    boolean nextUpperCase = false;
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);

      if (isWordSeparator(c)) {
        if (sb.length() > 0) {
          nextUpperCase = true;
        }
      } else {
        if (nextUpperCase) {
          sb.append(Character.toUpperCase(c));
          nextUpperCase = false;
        } else {
          sb.append(Character.toLowerCase(c));
        }
      }
    }

    if (firstCharacterUppercase) {
      sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    }
    return sb.toString();
  }

}

Related Tutorials