String to Char Array

Java-String to Char Array

String to Char Array

If we wish to extract more than one character at a time from a string, we have to use the getChars( ) method:

String to Char Array

For example:

String to Char Array

The characters staring from the position ‘3’ and ending with the position ‘8-1′ will be extracted and then stored in the character array ‘chararray’ from the position ‘3’ in the array ‘chararray’. Thus, in this example, ‘chararray’ will contain “DEFGH”.

Entire String to Char Array

The companion method for the getChars( ) method is the toCharArray( ). This method converts an entire string into an array of type char. For example:

String to Char Array

Program

String to Char Array

Program Source

public class Javaapp {

    public static void main(String[] args) {

        String str = "ABCDEFGH";
        char chararray[] = new char[8];
        str.getChars(3, 8, chararray, 3);
        for (char x : chararray) {
            
            System.out.print(x + ",");
        }
    }
}

Leave a Comment