Convert a String to a char array - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Convert a String to a char array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(java.util.Arrays.toString(strToChars(str)));
    }//from   w w  w  .j a v a 2s  .c om

    private static final char[] EMPTY_CHAR_ARRAY = new char[0];

    /**
     * Convert a String to a char array
     * @param str The string to convert
     * @return character array containing the characters in str. An
     *    empty array is returned if str is null.
     */
    public static char[] strToChars(String str) {
        int len;
        char[] ret;

        if (str == null)
            return EMPTY_CHAR_ARRAY;
        len = str.length();
        ret = new char[len];
        str.getChars(0, len, ret, 0);
        return ret;
    }
}

Related Tutorials