将数组中的元素连接成字符串 [英] Concatenating elements in an array to a string

查看:24
本文介绍了将数组中的元素连接成字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.我在任何地方都找不到答案;(

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

推荐答案

使用StringBuilder代替StringBuffer,因为它比StringBuffer快.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆