Concatenating elements in an array to a string

前端 未结 19 2334
慢半拍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 03:01

    Use the Arrays.toString() function. It keeps your code short and readable. It uses a string builder internally, thus, it's also efficient. To get rid of the extra characters, you might chose to eliminate them using the String.replace() function, which, admittedly, reduces readability again.

    String str = Arrays.toString(arr).replaceAll(", |\\[|\\]", "");
    

    This is similar to the answer of Tris Nefzger, but without the lengthy substring construction to get rid of the square brackets.

    Explanation of the Regex: "|" means any of ", " and "[" and "]". The "\\" tells the Java String that we are not meaning some special character (like a new line "\n" or a tab "\t") but a real backslash "\". So instead of "\\[", the Regex interpreter reads "\[", which tells it that we mean a literal square bracket and do not want to use it as part of the Regex language (for instance, "[^3]*" denotes any number of characters, but none of them should be "3").

提交回复
热议问题