本文介绍了concantenating数组中的元素为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我糊涂了一下。我找不到答案的任何地方;(
我有一个String数组:
的String [] ARR =1,2,3];
然后我将其转换为字符串:
字符串str = Arrays.toString(ARR);
的System.out.println(STR);
我希望得到字符串123
,但我得到字符串[1,2,3]
代替。
我怎么能做到这一点在Java中?我使用的Eclipse IDE
解决方案
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)
.
这篇关于concantenating数组中的元素为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!