concantenating数组中的元素为字符串 [英] concantenating elements in an array to a string
问题描述
我糊涂了一下。我找不到答案的任何地方;(
我有一个String数组:
的String [] ARR =1,2,3];
然后我将其转换为字符串:
字符串str = Arrays.toString(ARR);
的System.out.println(STR);
我希望得到字符串123
,但我得到字符串[1,2,3]
代替。
我怎么能做到这一点在Java中?我使用的Eclipse IDE
使用的StringBuilder 而不是StringBuffer的,因为它比StringBuffer的速度更快
块引用>的String [] = strArr {1,2,3};
StringBuilder的strBuilder =新的StringBuilder();
的for(int i = 0; I< strArr.length;我++){
strBuilder.append(strArr [I]);
}
串newString = strBuilder.toString();这也是为什么这是一个更好的解决方案,以使用字符串连接:当您连接两个字符串,创建一个新的字符串对象,并进行逐字符复制字符。结果有效这意味着code的复杂性将是平方的数组的大小顺序!
(
1 + 2 + 3 + ... N
这是每次迭代复制的字符数)。
的StringBuilder 会做的复制到一个字符串'只有在这种情况下,降低复杂性,一旦O(N)
。I'm confused a bit. I couldn't find the answer anywhere ;(
I've got an String array:
String[] arr = ["1", "2", "3"];
then I convert it to a string by:
String str = Arrays.toString(arr); System.out.println(str);
I expected to get the string
"123"
, but I got the string"[1,2,3]"
instead.How could I do it in java? I'm using Eclipse IDE
解决方案Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.
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 toO(n)
.这篇关于concantenating数组中的元素为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!