Java - Write code to Insert a string into a string array.

Requirements

Write code to Insert a string into a string array.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String[] array = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        String string = "book2s.com";
        int position = 42;
        System.out.println(java.util.Arrays.toString(insert(array, string,
                position)));/*from   w ww  . j  a  va2 s.c o  m*/
    }

    /**
     * Inserts a string into a string array. This is a costly operation as all array members
     * are copied to the result string array.
     *
     * @param array Specifies the string array in which to insert the string.
     * @param string Specifies the string to be inserted.
     * @param position Specifies the position at which to insert the string.
     * @return Returns a new array containing the string.
     */
    public static String[] insert(String[] array, String string,
            int position) {
        if (array == null)
            return (new String[] { string });

        String[] result = new String[array.length + 1];
        int index;
        for (index = 0; index < array.length + 1; ++index) {
            if (index < position && index < array.length)
                result[index] = array[index];

            if (index == position)
                result[index] = string;

            if (index > position)
                result[index] = array[index - 1];
        }

        if (index <= position)
            result[index - 1] = string;

        return (result);
    }
}

Related Exercise