Java Array append a char to char array

Description

Java Array append a char to char array


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        char[] c = new char[] { 'd', 'e', 'm', 'o', '2', 's', '.', 'c', 'o', 'm' };
        char toAdd = 'a';
        System.out.println(java.util.Arrays.toString(addChar(c, toAdd)));
    }/*from w  w w . j  a  v a 2 s . c om*/

    /**
     * Adds a char to an array of chars and returns the new array.
     *
     * @param c The chars to where the new char should be appended
     * @param toAdd the char to be added
     * @return a new array with the passed char appended.
     */
    public static char[] addChar(char[] c, char toAdd) {
        char[] c1 = new char[c.length + 1];

        System.arraycopy(c, 0, c1, 0, c.length);
        c1[c.length] = toAdd;
        return c1;

    }
}



PreviousNext

Related