File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/strings
test/java/com/thealgorithms/strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ StringBuilder result = new StringBuilder ();
29+ boolean capitalizeNext = true ;
30+ for (char c : input .toCharArray ()) {
31+ if (Character .isWhitespace (c )) {
32+ capitalizeNext = true ;
33+ result .append (c );
34+ } else if (capitalizeNext ) {
35+ result .append (Character .toUpperCase (c ));
36+ capitalizeNext = false ;
37+ } else {
38+ result .append (Character .toLowerCase (c ));
39+ }
40+ }
41+ return result .toString ();
42+ }
43+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .strings ;
2+ // author: Vraj Prajapati @Rosander0
3+
4+ import static org .junit .jupiter .api .Assertions .assertEquals ;
5+
6+ import org .junit .jupiter .api .Test ;
7+
8+ public class TitleCaseTest {
9+
10+ @ Test
11+ public void testNullOrEmptyInputs () {
12+ assertEquals ("" , TitleCase .toTitleCase (null ));
13+ assertEquals ("" , TitleCase .toTitleCase ("" ));
14+ }
15+
16+ @ Test
17+ public void testSingleWord () {
18+ assertEquals ("Hello" , TitleCase .toTitleCase ("hello" ));
19+ assertEquals ("Hello" , TitleCase .toTitleCase ("HELLO" ));
20+ assertEquals ("A" , TitleCase .toTitleCase ("a" ));
21+ }
22+
23+ @ Test
24+ public void testMultipleWords () {
25+ assertEquals ("The Quick Brown Fox" , TitleCase .toTitleCase ("the quick brown fox" ));
26+ assertEquals ("The Quick Brown Fox" , TitleCase .toTitleCase ("THE QUICK BROWN FOX" ));
27+ assertEquals ("Already Title Case" , TitleCase .toTitleCase ("already Title Case" ));
28+ }
29+
30+ @ Test
31+ public void testWhitespace () {
32+ assertEquals (" Spaces " , TitleCase .toTitleCase (" spaces " ));
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments