Concatenating elements in an array to a string

前端 未结 19 2341
慢半拍i
慢半拍i 2020-12-08 02:43

I\'m confused a bit. I couldn\'t find the answer anywhere ;(

I\'ve got an String array:

String[] arr = [\"1\", \"2\", \"3\"];

then

19条回答
  •  一个人的身影
    2020-12-08 02:58

    Arrays.toString: (from the API, at least for the Object[] version of it)

    public static String toString(Object[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";
    
        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(String.valueOf(a[i]));
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
    

    So that means it inserts the [ at the start, the ] at the end, and the , between elements.

    If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)

    String str = "";
    for (String i:arr)
      str += i;
    System.out.println(str);
    

    Side note:

    String[] arr[3]= [1,2,3] won't compile.

    Presumably you wanted: String[] arr = {"1", "2", "3"};

提交回复
热议问题