0

There is a code which capitalize first word letter. However I wasn't able to find a method to convert char array back to String:

For example: "hello world" code transforms it to ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"] I want to transform it back to "Hello World"

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

        char[] chars = s.toCharArray();
        chars[0] = Character.toUpperCase(chars[0]);

        for (int i = 0; i < chars.length; i++){
            if (chars[i] == ' '){
                chars[i + 1] = Character.toUpperCase(chars[i + 1]);
            }
        }
        System.out.println(chars);
    }
}
Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Baurzhan Kozhaev
  • 113
  • 1
  • 3
  • 7

2 Answers2

4
String str = String.valueOf( chars );

or

String str = new String( chars );
sinclair
  • 2,812
  • 4
  • 24
  • 53
0

Two other remarks:

  • In your approach, you should make sure, that the [i+1] element actually exists. A String like "Test ", ending with a space, would throw an ArrayIndexOutOfBoundsException in your code.

  • You should either close the Reader, or better: use a try-with-resources block like

try( BufferedReder reader = new InputStreamReader(System.in) ) { ... } catch( ... ) { ... }

which closes the Reader for you.

neurotic-d
  • 76
  • 1
  • 6