Reputation: 123
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);
}
}
Upvotes: 0
Views: 2565
Reputation: 76
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.
Upvotes: 0
Reputation: 2861
String str = String.valueOf( chars );
or
String str = new String( chars );
Upvotes: 4