|
| 1 | +package com.thealgorithms.strings; |
| 2 | + |
| 3 | +/** |
| 4 | + * Title Case converts a string so that the first letter of each word |
| 5 | + * is capitalized and the rest are lowercase. |
| 6 | + * Example: "the quick brown fox" -> "The Quick Brown Fox" |
| 7 | + * |
| 8 | + * @see <a href="https://en.wikipedia.org/wiki/Title_case"> |
| 9 | + * Wikipedia: Title Case</a> |
| 10 | + */ |
| 11 | +public final class TitleCase { |
| 12 | + |
| 13 | + private TitleCase() { |
| 14 | + // Utility class |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Converts a string to title case. |
| 19 | + * |
| 20 | + * @param input The string to convert |
| 21 | + * @return The title-cased string, or empty string if input is null/empty. |
| 22 | + * If input contains only whitespace, it is returned as is. |
| 23 | + */ |
| 24 | + public static String toTitleCase(final String input) { |
| 25 | + if (input == null || input.isEmpty()) { |
| 26 | + return ""; |
| 27 | + } |
| 28 | + |
| 29 | + StringBuilder result = new StringBuilder(input.length()); |
| 30 | + boolean capitalizeNext = true; |
| 31 | + for (int i = 0; i < input.length(); i++) { |
| 32 | + char c = input.charAt(i); |
| 33 | + if (Character.isWhitespace(c)) { |
| 34 | + capitalizeNext = true; |
| 35 | + result.append(c); |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + if (capitalizeNext) { |
| 40 | + if (Character.isLetter(c)) { |
| 41 | + result.append(Character.toUpperCase(c)); |
| 42 | + capitalizeNext = false; |
| 43 | + } else { |
| 44 | + // Keep capitalizeNext=true so the first *letter* after |
| 45 | + // punctuation/digits is capitalized. |
| 46 | + result.append(c); |
| 47 | + } |
| 48 | + } else { |
| 49 | + result.append(Character.toLowerCase(c)); |
| 50 | + } |
| 51 | + } |
| 52 | + return result.toString(); |
| 53 | + } |
| 54 | +} |
0 commit comments