Convert int[] to comma-separated string

后端 未结 6 730
情深已故
情深已故 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条回答
  • 2021-01-13 00:05

    Here's a stream version which is functionally equivalent to khelwood's, yet uses different methods.

    They both create an IntStream, map each int to a String and join those with commas.

    They should be pretty identical in performance too, although technically I'm calling Integer.toString(int) directly whereas he's calling String.valueOf(int) which delegates to it. On the other hand I'm calling IntStream.of() which delegates to Arrays.stream(int[]), so it's a tie.

    String result = IntStream.of(intArray)
                             .mapToObj(Integer::toString)
                             .collect(Collectors.joining(", "));
    
    0 讨论(0)
  • 2021-01-13 00:15

    This should do

    String arrAsStr = Arrays.toString(intArray).replaceAll("\\[|\\]", "");
    

    After Arrays toString, replacing the [] gives you the desired output.

    0 讨论(0)
  • 2021-01-13 00:16

    In java 8 you can use:

    String joined = String.join(",", iteratable);
    
    0 讨论(0)
  • 2021-01-13 00:22
            int[] intArray = {234, 808, 342, 564};
            String s = Arrays.toString(intArray);
            s = s.substring(1,s.length()-1);
    

    This should work. basic idea is to get sub string from Arrays.toString() excluding first and last character

    If want quotation in result, replace last line with:

    s = "\"" + s.substring(1,s.length()-1) + "\"";
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2021-01-13 00:24

    You want to convert the ints to strings, and join them with commas. You can do this with streams.

    int[] intArray = {234, 808, 342};
    String s = Arrays.stream(intArray)
                     .mapToObj(String::valueOf) // convert each int to a string
                     .collect(Collectors.joining(", ")); // join them with ", "
    

    Result:

    "234, 808, 342"
    
    0 讨论(0)
提交回复
热议问题