How to convert String to Char array - Stack Overflow

How to convert String to Char array.

  1. String.toCharArray()
  2. Stream

String.toCharArray()

String.toCharArray() converts the characters in String to a char array.

public void stringToCharArray1() {
    String string = "HelloWorld";
    char[] charArray = string.toCharArray();

    for (char ch: charArray) {
        System.out.println(ch);
    }
}

result

H
e
l
l
o
W
o
r
l
d

Stream

This is not a conversion to char[], but a code that individually outputs the characters of a String using a Stream. String.chars() creates a stream of characters in String.

public void stringToCharArray2() {
    String string = "HelloWorld";
    string.chars().mapToObj(ch -> (char)ch).forEach(System.out::println);
}

result

H
e
l
l
o
W
o
r
l
d
codechachaCopyright ©2019 codechacha