Convert String to Proper Case - Java java.lang

Java examples for java.lang:String Case

Description

Convert String to Proper Case

Demo Code


//package com.java2s;

public class Main {


    public static String toProperCase(String string) {
        String[] words = string.split(" ");
        String finalTitle = "";
        for (String word : words) {
            if (word.matches("[\\-(,].*")) {
                finalTitle = finalTitle + word.substring(0, 1);
                word = word.substring(1);
            }/* w  w  w  .j  a  v a 2s  .c  o  m*/
            if (word.length() == 0) {
                continue;
            }
            if (word.length() == 1) {
                finalTitle = finalTitle + word.toUpperCase() + " ";
            } else if (word.length() > 1) {
                finalTitle = finalTitle
                        + word.substring(0, 1).toUpperCase()
                        + word.substring(1).toLowerCase() + " ";
            }
        }
        finalTitle = finalTitle.substring(0, finalTitle.length() - 1);
        words = finalTitle.split(",");
        finalTitle = "";
        for (String word : words) {
            if (word.matches("[\\-(].*")) {
                finalTitle = finalTitle + word.substring(0, 1);
                word = word.substring(1);
            }
            if (word.length() == 0) {
                continue;
            }
            if (word.length() == 1) {
                finalTitle = finalTitle + word.toUpperCase() + ",";
            } else if (word.length() > 1) {
                finalTitle = finalTitle
                        + word.substring(0, 1).toUpperCase()
                        + word.substring(1) + ",";
            }
        }
        finalTitle = finalTitle.substring(0, finalTitle.length() - 1);
        words = finalTitle.split("'");
        finalTitle = "";
        for (String word : words) {
            if (word.length() == 1) {
                finalTitle = finalTitle + word.toUpperCase() + "'";
            } else if (word.length() > 1) {
                finalTitle = finalTitle
                        + word.substring(0, 1).toUpperCase()
                        + word.substring(1) + "'";
            }
        }
        finalTitle = finalTitle.substring(0, finalTitle.length() - 1);
        return finalTitle;
    }
}

Related Tutorials