How to convert a String array to char array in Java

前端 未结 6 1700
孤城傲影
孤城傲影 2020-12-10 00:33

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings For example:

Input: [i, love, you]

output:

6条回答
  •  再見小時候
    2020-12-10 01:04

    In Java 8 we can use streams.

    public char[] convert(String[] words) {
        return Arrays.stream(words)
                .collect(Collectors.joining())
                .toCharArray();
    }
    

    Here we created a stream from an array using Array.stream(T[] array) where T is the type of the array elements. Than we obtain a string using Collectors.joining(). Finally we get a char array using the String's toCharArray() method.

提交回复
热议问题