Add String to beginning of String array

前端 未结 9 1078
孤独总比滥情好
孤独总比滥情好 2021-01-01 09:44

Is it possible to add a string to beginning of String array without iterating the entire array.

9条回答
  •  猫巷女王i
    2021-01-01 10:24

    You can do some thing like below

    public class Test {
    
    public static String[] addFirst(String s[], String e) {
        String[] temp = new String[s.length + 1];
        temp[0] = e;
        System.arraycopy(s, 0, temp, 1, s.length);
        return temp;
    }
    
    public static void main(String[] args) {
        String[] s = { "b", "c" };
        s = addFirst(s, "a");
        System.out.println(Arrays.toString(s));
    }
    }
    

提交回复
热议问题