Java - Write code to convert a String to Sentence Case

Requirements

Write code to convert a String to Sentence Case

Demo

//package com.book2s;
import java.util.HashSet;

public class Main {
    public static void main(String[] argv) {
        String str = "this is a test";
        System.out.println(toSentenceCase(str));
    }//from   ww w .j  a  va 2  s  .c o m

    public static String toSentenceCase(String str) {
        if (!empty(str)) {
            String f = str.charAt(0) + ""; //First Letter
            HashSet ups = new HashSet();
            String n = ""; //new String

            for (int i = 0; i < str.length(); i++)
                if (Character.isUpperCase(str.charAt(i)))
                    ups.add(i);

            str = f.toUpperCase() + str.substring(1).toLowerCase();
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (ups.contains(i))
                    c = Character.toUpperCase(c);

                n += c;
            }

            return n;
        }
        return str;
    }

    public static boolean empty(String str) {
        return str == null || str.length() == 0;
    }
}

Related Exercise