format Unit to String - Java java.lang

Java examples for java.lang:String Format

Description

format Unit to String

Demo Code


//package com.java2s;

public class Main {


    public static String formatUnit(String unit) {
        if (unit.contains("ea")) {
            return ("Each");
        }/*from w  w w .  ja  va2  s.  c  om*/
        if (unit.contains("cs") || unit.trim().length() == 0) {
            return ("Case");
        }
        if (unit.contains("lb")) {
            return ("Pound");
        }
        if (unit.contains("pc")) {
            return ("Piece");
        }
        if (unit.contains("pkg")) {
            return ("Package");
        }
        return toProperCase(unit);
    }

    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);
            }
            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