可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am printing out elements from a array list, I want to have a comma between each word except the last word. Right now I am doing like this:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
As you understand it will print out the words like this: "one, two, three, four,"
and the problem is the last comma, how do I solve this? All answers appreciated!
Best regards,
Erica
回答1:
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
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
回答2:
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
回答3:
Using Java 8 Streams:
Stream.of(arrayListWords).collect(Collectors.joining(", "));
回答4:
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
)
StringBuilder res = new StringBuilder();
for (String s : arrayListWords) {
res.append(s).append(", ");
}
System.out.println(res.deleteCharAt(res.length()-2).toString());
回答5:
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
回答6:
You could use a standard function in the java.util package and remove the block quotes at start and end.
String str = java.util.Arrays.toString(arrayListWords);
str = str.substring(1,str.length()-1);
System.out.println(str);
回答7:
You can use an Iterator
on the List
to check whether there are more elements.
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. 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));
}
回答8:
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("\\[|\\]",""));
回答9:
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.
回答10:
With Java 8 it got much easier, no need for 3rd parties -
final List<String> words = Arrays.asList("one", "two", "three", "four");
String wordsAsString = words.stream().reduce((w1, w2) -> w1 + "," + w2).get();
System.out.println(wordsAsString);
回答11:
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.
Also having a "size" variable reduces the calls to the .size()
method.
For those using 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>
:
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
回答12:
Just use the toString() method.
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.