I recently was given a task to capitalize the first character of a string provided the string does not begin with a non-alphabet. Below are the requirements and my implementation. Just want to know if there is a more efficient way to implement this.
Requirements
Please implement this method to capitalize all first letters of the words in the given String. All other symbols shall remain intact. If a word starts not with a letter, it shall remain intact too.Assume that the parameter String can only contain spaces and alphanumeric characters. NOTE: please keep in mind that the words can be divided by single or multiple spaces.The spaces also can be found at the beginning or the end of the parameter string,and you need to preserve them.
public static String capitalizeFirstLetters(String s) {
StringBuilder wordsWithFirstLetterCapitalized = new StringBuilder();
s = s.trim();
String words[] = s.split("\\ ");
if (words.length <= 1) {
if(words.toString().matches("^[A-Za-z].*$")) {
words.toString().toUpperCase();
wordsWithFirstLetterCapitalized.append(words);
}
else {
wordsWithFirstLetterCapitalized.append(words);
}
}
else {
for (String word : words) {
if (word.matches("^[A-Za-z].*$")) {
word = word.substring(0, 1).toUpperCase() + word.substring(1);
wordsWithFirstLetterCapitalized.append(word);
wordsWithFirstLetterCapitalized.append(" ");
}
else {
wordsWithFirstLetterCapitalized.append(word);
}
}
}
return wordsWithFirstLetterCapitalized.toString();
}