Convert int[] to comma-separated string

后端 未结 6 768
情深已故
情深已故 2021-01-12 23:45

How can I convert int[] to comma-separated String in Java?

int[] intArray = {234, 808, 342};

Result I want:

\"         


        
6条回答
  •  Happy的楠姐
    2021-01-13 00:23

    This is the pattern I always use for separator-joining. It's a pain to write this boilerplate every time, but it's much more efficient (in terms of both memory and processing time) than the newfangled Stream solutions that others have posted.

    public static String toString(int[] arr) {
        StringBuilder buf = new StringBuilder();
        for (int i = 0, n = arr.length; i < n; i++) {
            if (i > 0) {
                buf.append(", ");
            }
            buf.append(arr[i]);
        }
        return buf.toString();
    }
    

提交回复
热议问题