如何将数组列表转换为字符串?
问题描述:
我是 Java 初学者.在我的代码中,我有一个数组列表,我想完全输出为字符串.为此,我编写了这段代码.
I am beginner in java. In my code i have a arraylist and i want to output completely as a String. for this i have write this code.
package factorytest;
import java.util.ArrayList;
import java.util.List;
public class MatchingWord {
public static void main(String[] args) {
List <String> myList = new ArrayList<String>();
myList.add("hello");
myList.add("first");
myList.add("second");
myList.add("third");
myList.add("fourth");
// 1st approach
String listString = "";
for (String s : myList)
{
listString += s + "\t";
}
System.out.println(listString);
}
}
我的输出是
hello first second third fourth
我不想要最后一个元素之后的最后一个 \t.我怎样才能做到这一点.
i don't want the last \t after the last element. how can i achieve this.
答
一个解决方案是不使用 for-each 循环,您可以执行以下操作:
One solution is not using for-each loop, you can do the following:
int i;
for(i = 0;i < myList.size() - 1;i++) {
listString += myList.get(i) + "\t";
}
listString += myList.get(i);
我建议您使用 StringBuilder
而不是 +
.
其他解决方案:
- 完成构造后修剪字符串.
- 使用
Joiner
. - ...