有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中如何在字符串数组之间添加逗号/和

我从json响应中获得一个作者数组,我必须以适当的格式在TextView(安卓)中显示作者姓名,如=>;维拉伊、切坦和乔治·R·R·马丁 我的代码运行得很好,但很混乱

public class SeprateAuthors {
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};
    
    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));        
}
public static String displayAuthors(String[] authors) {
    StringBuilder stringBuilder = new StringBuilder();
    String stringAuthors="";
    String prefixComma = ", ";
    String prefixAnd = " and ";
    if ((authors != null) && (authors.length > 0)) {
        
        for (int i = 0; i < authors.length; i++) {
            if (i < authors.length - 2) {
                stringBuilder.append(authors[i]).append(prefixComma);
            } else {
                stringBuilder.append(authors[i]).append(prefixAnd);
            }
        }
        //  Java Remove extra Characters("and ") from String
        stringAuthors = stringBuilder.substring(0, stringBuilder.length() - 4);
    }
    return stringAuthors;
}

}


共 (1) 个答案

  1. # 1 楼答案

    import java.util.Arrays;
    import java.util.List;
    
    class SeprateAuthors {
    
        public static void main(String[] args) {
            String[] authors0 = {"a", "b"};
            String[] authors1 = {"a", "b", "c"};
            String[] authors2 = {"a", "b", "c", "d"};
            String[] authors3 = {"a", "b", "c", "d", "e", "f"};
    
            System.out.println(displayAuthors(authors0));
            System.out.println(displayAuthors(authors1));
            System.out.println(displayAuthors(authors2));
            System.out.println(displayAuthors(authors3));
        }
    
        public static String displayAuthors(String[] authorsArray) {
    
            List<String> authors = Arrays.asList(authorsArray);
    
            if (authors.size() == 1) {
                return authors.get(0);
            } else {
                String lastAuthor = authors.get(authors.size() - 1);
                List<String> firstAuthors = authors.subList(0, authors.size() - 1);
    
                String firstAuthorsString = String.join(", ", firstAuthors);
    
                return  firstAuthorsString + " and " + lastAuthor;
            }
        }
    }
    

    这应该对你有用

    输出:

    a and b
    a, b and c
    a, b, c and d
    a, b, c, d, e and f