Skip to content
Advertisement

Capitalization of the words in string

How can I avoid of StringIndexOutOfBoundsException in case when string starts with space (” “) or when there’re several spaces in the string? Actually I need to capitalize first letters of the words in the string.

My code looks like:

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String s = reader.readLine();
    String[] array = s.split(" ");

    for (String word : array) {
        word = word.substring(0, 1).toUpperCase() + word.substring(1); //seems that here's no way to avoid extra spaces
        System.out.print(word + " ");
    }
}

Tests:

Input: "test test test"

Output: "Test Test Test"


Input: " test test test"

Output:

StringIndexOutOfBoundsException

Expected: " Test Test test"

I’m a Java newbie and any help is very appreciated. Thanks!

Advertisement

Answer

A slight modification to Capitalize first word of a sentence in a string with multiple sentences.

public static void main( String[] args ) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String s = reader.readLine();

    int pos = 0;
    boolean capitalize = true;
    StringBuilder sb = new StringBuilder(s);
    while (pos < sb.length()) {
        if (sb.charAt(pos) == ' ') {
            capitalize = true;
        } else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
            sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
            capitalize = false;
        }
        pos++;
    }
    System.out.println(sb.toString());
}

I would avoid using split and go with StringBuilder instead.

Advertisement