简体   繁体   中英

How to convert char array back to string

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);
    }
}
String str = String.valueOf( chars );

要么

String str = new String( chars );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM