[英]Print out elements from an Array with a Comma between the elements
I am printing out elements from an ArrayList
and want to have a comma after each word except the last word.我正在打印
ArrayList
中的元素,并且希望在除最后一个单词之外的每个单词之后有一个逗号。
Right now, I am doing it like this:现在,我正在这样做:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
It prints out the words like this:它打印出这样的单词:
one, two, three, four,
The problem is the last comma.问题是最后一个逗号。 How do I solve it?
我该如何解决?
Print the first word on its own if it exists.如果存在,则自行打印第一个单词。 Then print the pattern as comma first, then the next element.
然后首先将模式打印为逗号,然后是下一个元素。
if (arrayListWords.length >= 1) {
System.out.print(arrayListWords[0]);
}
// note that i starts at 1, since we already printed the element at index 0
for (int i = 1; i < arrayListWords.length, i++) {
System.out.print(", " + arrayListWords[i]);
}
With a List
, you're better off using an Iterator
使用
List
,最好使用Iterator
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
I would write it this way:我会这样写:
String separator = ""; // separator here is your ","
for (String s : arrayListWords) {
System.out.print(separator + s);
separator = ",";
}
If arrayListWords has two words, it should print out A,B如果 arrayListWords 有两个单词,它应该打印出 A,B
使用 Java 8 流:
Stream.of(arrayListWords).collect(Collectors.joining(", "));
StringJoiner str = new StringJoiner(", ");
str.add("Aplha").add("Beta").add("Gamma");
String result = str.toString();
System.out.println("The result is: " + result);
The output: The result is: Aplha, Beta, Gamma输出: 结果是:Aplha、Beta、Gamma
While iterating, you can append the String s
to the StringBuilder
and at the end, you can delete the last 2 chars which is an extra ,
and a space ( res.length() -2
)虽然迭代,你可以附加
String s
到StringBuilder
,并在结束时,你可以删除最后2个字符是一个额外的,
和一个空格( res.length() -2
)
StringBuilder res = new StringBuilder();
for (String s : arrayListWords) {
res.append(s).append(", ");
}
System.out.println(res.deleteCharAt(res.length()-2).toString());
With Java 8 it got much easier, no need for 3rd parties -有了 Java 8,它变得更容易了,不需要第三者——
final List<String> words = Arrays.asList("one", "two", "three", "four");
Optional<String> wordsAsString = words.stream().reduce((w1, w2) -> w1 + "," + w2);
wordsAsString.ifPresent(System.out::println);
You could use a standard function in the java.util package and remove the block quotes at start and end.您可以使用 java.util 包中的标准函数并删除开头和结尾的块引号。
String str = java.util.Arrays.toString(arrayListWords);
str = str.substring(1,str.length()-1);
System.out.println(str);
You can use an Iterator
on the List
to check whether there are more elements.您可以在
List
上使用Iterator
来检查是否有更多元素。
You can then append the comma only if the current element is not the last element.只有当当前元素不是最后一个元素时,您才能附加逗号。
public static void main(String[] args) throws Exception {
final List<String> words = Arrays.asList(new String[]{"one", "two", "three", "four"});
final Iterator<String> wordIter = words.iterator();
final StringBuilder out = new StringBuilder();
while (wordIter.hasNext()) {
out.append(wordIter.next());
if (wordIter.hasNext()) {
out.append(",");
}
}
System.out.println(out.toString());
}
However it is much easier to use a 3rd party library like Guava to do this for you.然而,使用像Guava这样的 3rd 方库来为你做这件事要容易得多。 The code then becomes:
然后代码变成:
public static void main(String[] args) throws Exception {
final List<String> words = Arrays.asList(new String[]{"one", "two", "three", "four"});
System.out.println(Joiner.on(",").join(words));
}
You can try this你可以试试这个
List<String> listWords= Arrays.asList(arrayListWords); // convert array to List
StringBuilder sb=new StringBuilder();
sb.append(listWords);
System.out.println(sb.toString().replaceAll("\\[|\\]",""));
Just use the toString() method.只需使用 toString() 方法。
String s = arrayListWords.toString();
System.out.println(s);
//This will print it like this: "[one, two, three, four]"
//If you want to remove the brackets you can do so easily. Just change the way you print.
Here is what I come up with:这是我想出的:
String join = "";
// solution 1
List<String> strList = Arrays.asList(new String[] {"1", "2", "3"});
for(String s: strList) {
int idx = strList.indexOf(s);
join += (idx == strList.size()-1) ? s : s + ",";
}
System.out.println(join);
// solution 2
join = "";
for(String s: strList) {
join += s + ",";
}
join = join.substring(0, join.length()-1);
System.out.println(join);
// solution 3
join = "";
int count = 0;
for(String s: strList) {
join += (count == strlist.size()-1) ? s: s + ",";
count++;
}
System.out.println(join);
off course we can utalise StringBuilder
but of all solutions, I like @Mav
answer as it's more efficient and clean.当然,我们可以使用
StringBuilder
但在所有解决方案中,我喜欢@Mav
答案,因为它更高效、更干净。
This might be the most efficient means of comma-delimited string using best practices and no "if" checks, no unfamiliar libraries, and StringBuilder
which is best practice for concatenating strings.这可能是使用最佳实践的逗号分隔字符串的最有效方法,没有“if”检查,没有不熟悉的库,并且
StringBuilder
是连接字符串的最佳实践。
Also having a "size" variable reduces the calls to the .size()
method.还有一个“size”变量可以减少对
.size()
方法的调用。
For those using String[]
:对于那些使用
String[]
:
StringBuilder str = new StringBuilder();
String[] strArr = {"one", "two", "three", "four"};
int size = strArr.length;
str.append(strArr[0]);
for (int i = 1; i < size; i++) {
str.append(",").append(strArr[i]);
}
System.out.println(str.toString());
For those using ArrayList<String>
:对于那些使用
ArrayList<String>
:
StringBuilder str = new StringBuilder();
List<String> strArr = Arrays.asList(new String[]{"one", "two", "three", "four"});
int size = strArr.size();
str.append(strArr.get(0));
for (int i = 1; i < size; i++) {
str.append(",").append(strArr.get(i));
}
System.out.println(str.toString());
Both yield: one,two,three,four
两者产量:
one,two,three,four
Since the second-to-top question was wrong, here's a little method I wrote to do this with an array of Integers but converted to array of Strings.由于倒数第二个问题是错误的,这是我编写的一个小方法,用于使用整数数组执行此操作,但转换为字符串数组。
public static void printArray(String[] arr){
for(int i = 0;i<arr.length;i++){
System.out.print(arr[i]);
if(i<(arr.length-1))
System.out.print(",");
}
}
It can also be done using Java 8 static
method String.join()
, which comes in two flavors.也可以使用 Java 8
static
方法String.join()
来完成,它有两种风格。
Returns a new
String
composed of copies of theCharSequence
elements joined together with a copy of the specifieddelimiter
.返回由
CharSequence
元素的副本和指定delimiter
的副本连接在一起的新String
。
Both versions expect as the first argument delimiter
of type CharSequence
, and as the second argument we can provide either varargs of CharSequence
or Iterable<? extends CharSequence>
两个版本都期望作为
CharSequence
类型的第一个参数delimiter
,作为第二个参数,我们可以提供CharSequence
的可变参数或Iterable<? extends CharSequence>
Iterable<? extends CharSequence>
. Iterable<? extends CharSequence>
。
Both methods generate under the hood a byte
-array filled byte representations of the provided elements and delimiter according to their encoding and then turn it into the resulting String
.这两种方法都根据它们的编码在引擎盖下生成一个
byte
数组填充的所提供元素和分隔符的字节表示,然后将其转换为结果String
。
Example with String.join(CharSequence,CharSequence...)
: String.join(CharSequence,CharSequence...)
的示例:
String[] strings = {"one", "two", "three", "four"};
String joinedStr = String.join(", ", strings); // "one, two, three, four" - resulting String
Example with String.join(CharSequence,Iterable<? extends CharSequence>)
: String.join(CharSequence,Iterable<? extends CharSequence>)
的示例:
List<String> strings = List.of("one", "two", "three", "four");
String joinedStr = String.join(", ", strings); // "one, two, three, four" - resulting String
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.