How to check if a string is title case in Java

1 Answer

0 votes
public class TitleCaseCheck {

    public static boolean isTitleCase(String s) {
        boolean newWord = true;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (Character.isWhitespace(c)) {
                newWord = true;
            } else {
                if (newWord) {
                    if (!Character.isUpperCase(c)) {
                        return false;
                    }
                    newWord = false;
                } else {
                    if (!Character.isLowerCase(c)) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String[] tests = {
            "Hello World",
            "Hello world",
            "hello World",
            "Java Programming Language",
            "This Is Fine",
            "This is Not Fine"
        };

        for (String t : tests) {
            System.out.println("\"" + t + "\" -> " + isTitleCase(t));
        }
    }
}



/*
run:

"Hello World" -> true
"Hello world" -> false
"hello World" -> false
"Java Programming Language" -> true
"This Is Fine" -> true
"This is Not Fine" -> false

*/

 



answered 10 hours ago by avibootz
...