C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Character: We use the Character class and the toUpperCase method to uppercase the first element in the char array.
Finally: We use the String constructor to convert our modified char array back into a String.
Char Array, StringJava program that uppercases first letter
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);
}
}
Output
carrot
Carrot
steamed carrot
Steamed carrot
But: It then searches the String for additional words. It uses Character.isWhitespace to find word breaks.
And: It invokes Character.toUpperCase to capitalize non-first words in the String.
Java program that uppercases all words
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);
}
}
Output
cat 123 456
Cat 123 456
one two three
One Two Three
And: An algorithm that capitalizes words can become complicated. We keep the logic simple, but it will not work in all cases.
Caution: For words with hyphens, like names ("Boyer-Moore" for example) the logic will not capitalize the second word.
Further: For short words like "A" the word will always be capitalized, even if this is not appropriate.
Often: Some special-casing logic in our code is sufficient to fix many small issues. Sometimes even this is not required.