我有一个ArrayList
,我想完全输出为一个字符串,用comma
分隔。
我的代码是
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (String s : list)
{
listString += s + ",";
}
System.out.println(listString);
但输出为one,two,three,
,我希望one,two,three
不使用replace method
。
我正在使用JAVA
答案 0 :(得分:4)
使用Java 8:
List<String> list = Arrays.asList(array);
String joinedString = String.join(",", list);
答案 1 :(得分:0)
UIDatePicker * datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake ( 0.0, 44.0, 0.0, 0.0)];
[datePicker setBackgroundColor:[UIColor whiteColor]];
datePicker.datePickerMode = UIDatePickerModeDate;
[Self.view addSubView:datePicker];
输出:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (int i=0;i<list.size()-1;i++)
listString += list.get(i) + ",";
System.out.println(listString+list.get(list.size()-1));
}
}
答案 2 :(得分:0)
在Java 8+中,您可以使用StringJoiner
(并且可以使用Arrays.asList(T...)
初始化List
)。像,
List<String> list = Arrays.asList("one", "two", "three");
StringJoiner sj = new StringJoiner(",");
for (String s : list) {
sj.add(s);
}
System.out.println(sj.toString());
输出(按要求)
one,two,three
答案 3 :(得分:0)
只需使用String.substring
即可。你走了:
listString = listString.substring(0, listString.length() - 1);
答案 4 :(得分:0)
您可以使用java.util.StringJoiner而不是List:
StringJoiner joiner = new StringJoiner(",");
joiner.add("one");
joiner.add("two"),
joiner.add("three");
String listString = joiner.toString();
如果您不使用Java8,请考虑使用StringBuilder。然后你的最后一个字符串可以是:
System.out.println(listString.substring(0, listString.length() - 1));
答案 5 :(得分:0)
对于Java 8之前的解决方案,因为默认toString()
会为您提供[one, two, three]
。
String s = list.toString();
s = s.substring(1, s.length()-1);
答案 6 :(得分:0)
试
list.toString().replace("[", "").replace("]", "");