Concatenating elements in an array to a string

前端 未结 19 2270
慢半拍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").

    0 讨论(0)
  • 2020-12-08 03:01

    Example using Java 8.

      String[] arr = {"1", "2", "3"};
      String join = String.join("", arr);
    

    I hope that helps

    0 讨论(0)
  • 2020-12-08 03:04

    I have just written the following:

    public static String toDelimitedString(int[] ids, String delimiter)
    {
        StringBuffer strb = new StringBuffer();
        for (int id : ids)
        {
          strb.append(String.valueOf(id) + delimiter);
        }
        return strb.substring(0, strb.length() - delimiter.length());
     }
    
    0 讨论(0)
  • 2020-12-08 03:04
    String newString= Arrays.toString(oldString).replace("[","").replace("]","").replace(",","").trim();
    
    0 讨论(0)
  • 2020-12-08 03:08

    Do it java 8 way in just 1 line:

    String.join("", arr);

    0 讨论(0)
  • 2020-12-08 03:10

    For Spring based projects:

    org.springframework.util.StringUtils.arrayToDelimitedString(Object[] arr, String delim)

    For Apache Commons users, set of nice join methods:

    org.apache.commons.lang.StringUtils.join(Object[] array, char separator)

    0 讨论(0)
提交回复
热议问题