[英]Insert semicolon between items from an array except the last
Based from the accepted answer from this post , I have this code: 从接受基础的答案 ,从这个帖子 ,我有这样的代码:
if (authors.length >= 1) {
System.out.print(authors[0]);
}
for (int i = 1; i < authors.length; i++) {
System.out.print("; " + authors[i]);
}
So the output of this is author1; author2; author3
这样的输出是author1; author2; author3
author1; author2; author3
author1; author2; author3
How can I change this into author1; author2 & author3
author1; author2; author3
我怎样才能改变这个author1; author2 & author3
author1; author2 & author3
? author1; author2 & author3
吗? If there are only 2 authors, the output should be author1 & author2
. 如果只有2个作者,则输出应为author1 & author2
。 Thanks in advance. 提前致谢。
You'd just need to add in one conditional to your loop to handle the last case: 您只需要在循环中添加一个条件即可处理最后一种情况:
for (int i = 1; i < authors.length; i++) {
if(i == authors.length - 1)
System.out.print("& " + authors[i]);
else
System.out.print("; " + authors[i]);
}
One way to do it would be changing the structure of the code to use a loop and a boolean
flag instead of a conditional, like this: 一种方法是将代码的结构更改为使用循环和boolean
标志而不是条件的,例如:
boolean isFirst = true;
for (int i = 0 ; i != authors.length ; i++) {
if (!isFirst) {
System.out.print(i == authors.length-1 ? "& " : "; ");
} else {
isFirst = false;
}
System.out.print(authors[i]);
}
You can do it recursively to separate cases clearly. 您可以递归地执行此操作以清楚地区分案例。 Seems like other answers lack that. 似乎没有其他答案。
This is the proxy function: 这是代理功能:
public static String doIt(String[] authors){
if (authors == null || authors.length == 0){
return "";
}
if (authors.length == 1){
return authors[0];
}
return authors[0] + doHelper(authors, 1);
}
And the helper function: 和助手功能:
public static String doItHelper(String[] authors, int index){
if (index == authors.length - 1){
return " & " + authors[index];
}
return "; " + authors[index] + doItHelper(authors, index + 1);
}
As mentioned in comments (Thanks @JNYRanger) this is not optimal when performance is an issue. 如评论中所述(感谢@JNYRanger),这在性能成为问题时不是最佳的。
Can't test it now, so I hope the idea is clear. 现在无法测试,所以我希望这个想法很明确。
Try it this way: 尝试这种方式:
String[] authors = { "1", "2", "3", "4", "5" };
StringBuffer sb = new StringBuffer();
for (int i = 0; i < authors.length; i++) {
sb.append(authors[i]);
if (i + 2 < authors.length) {
sb.append(";");
} else if (i + 2 == authors.length) {
sb.append("&");
}
}
System.out.print(sb.toString());
for (int i = 0; i < authors.length; i += 1) {
if (i > 0) {
System.out.print(i < authors.length - 1 ? "; " : " & ");
}
System.out.print(authors[i]);
}
String[] authors = {"a", "b", "c", "d"};
for (int i = 0; i < authors.length; i++) {
System.out.print((i != 0 ? (i == authors.length - 1 ? " & " : "; ") : "") + authors[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.