将数组中的元素连接到字符串 [英] Concatenating elements in an array to a string
问题描述
我有点困惑。我无法在任何地方找到答案;(
I'm confused a bit. I couldn't find the answer anywhere ;(
我有一个字符串数组:
String[] arr = ["1", "2", "3"];
然后我将它转换为字符串:
then I convert it to a string by:
String str = Arrays.toString(arr);
System.out.println(str);
我希望得到字符串123
,但我得到字符串[1,2,3]
而不是。
I expected to get the string "123"
, but I got the string "[1,2,3]"
instead.
我怎么能用java做?我正在使用Eclipse IDE
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();
这就是为什么这是使用字符串连接的更好解决方案:连接2个字符串时,新字符串创建对象并执行逐字符复制。
有效地意味着代码复杂性将是数组大小平方的顺序!
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
这是每个复制的字符数迭代)。
StringBuilder 只会在这种情况下执行'复制到字符串'一次,将复杂性降低到 O(n)
。
(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)
.
这篇关于将数组中的元素连接到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!