Concatenating elements in an array to a string

前端 未结 19 2338
慢半拍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条回答
  •  猫巷女王i
    2020-12-08 03:13

    Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.

    Sample code

    String[] strArr = {"1", "2", "3"};
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < strArr.length; i++) {
       strBuilder.append(strArr[i]);
    }
    String newString = strBuilder.toString();
    

    Here's why this is a better solution to using string concatenation: When you concatenate 2 strings, a new string object is created and character by character copy is performed.
    Effectively meaning that the code complexity would be the order of the squared of the size of your array!

    (1+2+3+ ... n which is the number of characters copied per iteration). StringBuilder would do the 'copying to a string' only once in this case reducing the complexity to O(n).

提交回复
热议问题