A String
needs an "Uppercase" first letter. It may contain two or more words—these also may need to be capitalized.
On the Java String
class
, we have toUpperCase
, but this acts on all letters. We can use toCharArray
and Character.toUpperCase
to capitalize only certain letters.
Let us start with a simple implementation. We introduce upperCaseFirst
. This method receives a String
and converts it to a char
array with toCharArray
.
class
and the toUpperCase
method to uppercase the first element in the char
array.String
constructor to convert our modified char
array back into a String
.public class Program { public static String upperCaseFirst(String value) { // Convert String to char array. char[] array = value.toCharArray(); // Modify first element in array. array[0] = Character.toUpperCase(array[0]); // Return string. return new String(array); } public static void main(String[] args) { String value = "carrot"; String value2 = "steamed carrot"; // Test the upperCaseFirst method. String result = upperCaseFirst(value); System.out.println(value); System.out.println(result); result = upperCaseFirst(value2); System.out.println(value2); System.out.println(result); } }carrot Carrot steamed carrot Steamed carrot
This method, upperCaseAllFirst
, is a more complex version of the previous method. It also uppercases the String
's first letter.
String
for additional words. It uses Character.isWhitespace
to find word breaks.Character.toUpperCase
to capitalize non-first words in the String
.public class Program { public static String upperCaseAllFirst(String value) { char[] array = value.toCharArray(); // Uppercase first letter. array[0] = Character.toUpperCase(array[0]); // Uppercase all letters that follow a whitespace character. for (int i = 1; i < array.length; i++) { if (Character.isWhitespace(array[i - 1])) { array[i] = Character.toUpperCase(array[i]); } } // Result. return new String(array); } public static void main(String[] args) { String value = "cat 123 456"; String value2 = "one two three"; // Test our code. String result = upperCaseAllFirst(value); System.out.println(value); System.out.println(result); result = upperCaseAllFirst(value2); System.out.println(value2); System.out.println(result); } }cat 123 456 Cat 123 456 one two three One Two Three
To modify a String
's individual letters, we can use toCharArray
to get a char
array. Then we can change letters in any way. We can test with Character methods.
short
words like "A" the word will always be capitalized, even if this is not appropriate.For ideal capitalization, a dictionary and lookup table (or directed acyclic graph) would need to be used. This problem rapidly becomes complex.
We developed a simple approach to capitalizing certain letters in Java Strings. We can use a for
-loop to locate optimal characters to uppercase.