prefixes str with "a " or "an ", capitalized appropriately - Java java.lang

Java examples for java.lang:String Capitalize

Description

prefixes str with "a " or "an ", capitalized appropriately

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(addArticle(str));
    }/*w w  w  . ja v  a  2  s .com*/

    private static final char[] LOWERCASE_VOWELS = new char[] { 'a', 'e',
            'i', 'o', 'u' };

    /**
     *  prefixes str with "a " or "an ", capitalized appropriately
     */
    public static String addArticle(String str) {
        if (str == null || str == "")
            return str; // do nothing

        char[] chars = str.toCharArray();
        char first = chars[0];

        if (!Character.isAlphabetic(first))
            return str; // do nothing

        boolean isVowel = contains(LOWERCASE_VOWELS,
                Character.toLowerCase(first));
        String rest = Character.toLowerCase(first) + str.substring(1);
        if (Character.isUpperCase(first)) {
            if (isVowel) {
                str = "An " + rest;
            } else {
                str = "A " + rest;
            }
        } else {
            if (isVowel) {
                str = "an " + rest;
            } else {
                str = "a " + rest;
            }
        }

        return str;
    }

    private static boolean contains(char[] chars, char ch) {
        for (char element : chars) {
            if (element == ch)
                return true;
        }

        return false;
    }
}

Related Tutorials