A method to capitalize the first letter of all words in a String 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 &lt;= 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();
    }
It appears whitespace is destroyed instead of preserved, see your "NOTE". I suspect input like " 123 456 " will output "123456" destroying outer and inner space.  Similarly "a     b" will become "A B", as split will return a lot of empty strings when splitting more than one space.  How about treating it as a stream and if the previous character is whitespace and the next character is in a-z, upper case it, and emit the character and update your previous character placeholder.  You could probably do this with a single regular expression.