简体   繁体   中英

How would I print out a string of arrays without the last comma?

for (String userName : studentEnrollments.keySet()) {
    System.out.println("Student: " + userName);
    ArrayList<String> courses = studentEnrollments.get(userName);
    String courseMessage = "Courses: ";
    for (String singleCourse : courses) {
        courseMessage += singleCourse + ", ";
        System.out.println(courseMessage);
    }
}

After the for loop, it prints out each courses the student is taking. What is the proper way to print out the string with commas without the last comma at the end?

For example: AC130, AC140, AC150, to AC130, AC140, AC150

Use a while with Iterator instead of for loop, then add a coma only if hasNext() returns true.

String courseMessage = "Courses: ";
Iterator<String> c = studentEnrollments.get(userName).iterator();

while (c.hasNext()) {
    courseMessage += c.next();
    if (c.hasNext()) {
        courseMessage += ",";
    }
}

请注意,在Java 8中,您可以使用StringJoiner

 String commaSeparatedCourses = courses.stream().collect(Collectors.joining(", "));

You can use StringUtils.join method from apache

Example :

StringUtils.join(studentEnrollments, ", ");

Here is another way to do it :

  • Define an empty string as a separator
  • Print the separator and the array element (in this order, the separator first)
  • Change the separator to a comma (or whatever you want)

This method reverse the problem : instead of adding a comma after each element except the last one, you add a comma before each element except the first one.

Here is an implementation

String separator = "";
for (String singleCourse : courses) {
    courseMessage += separator + singleCourse;
    System.out.println(courseMessage);
    separator = ",";
}

you could use a StringJoiner if you are using java 8

StringJoiner joiner = new StringJoiner(", ");
for (String singleCourse : courses) {
    joiner.add(singleCourse);
}
System.out.println(joiner.toString());

Otherwise you could just add the , previous to the string instead of appending it.

String courseMessage = "Courses: " + courses.get(0);
for (int i = 1; i<courses.size();++i) {
    courseMessage += ", " + courses.get(i);
}

With a StringBuilder:

for (String userName : studentEnrollments.keySet()) {
    System.out.println("Student: " + userName);
    ArrayList<String> courses = studentEnrollments.get(userName);
    StringBuilder sb = new StringBuilder();
    for (String singleCourse : courses) {
        if(sb.length()>0){
            sb.append(", ");
        }
        sb.append(singleCourse);
    }
    System.out.println(sb.insert(0, "Courses: ").toString());
}

Use StringBuilder instead

for (String userName : studentEnrollments.keySet()) {
    System.out.println("Student: " + userName);
    ArrayList<String> courses = studentEnrollments.get(userName);
    StringBuilder courseMessage = "Courses: ";
    for (String singleCourse : courses) {
        sb.append(singleCourse).append(", ");
    }
    if (sb.length() > 2) 
        sb.setLength(sd.length() -2);
    String courseMessage = sb.toString();
    System.out.println(courseMessage);
}

Or even better with StringUtils (from apache-common)

for (String userName : studentEnrollments.keySet()) {
    System.out.println("Student: " + userName);
    ArrayList<String> courses = studentEnrollments.get(userName);
    String courseMessage = sb.toString();
    System.out.println(StringUtils.join(courses, ", ");
}

For a solution prior Java 8 you also might have a look at this snippet as starting point

String[] courses ={ "AC130", "AC140", "AC150" };
for (int i = 0; i < courses.length - 1; i++) {
    System.out.append(courses[i]).append(", ");
}
System.out.println(courses[courses.length-1]);

Small explanation: for all elements but the last one it print "element" + ", " for the last element it print "element" only. You need to ensure yourself, that an empty array would not be processed.

Use string.replaceAll(", $", "") , as follows:

for (String userName : studentEnrollments.keySet()) {
            System.out.println("Student: " + userName);
            ArrayList<String> courses = studentEnrollments.get(userName);
            String courseMessage = "Courses: ";
            for (String singleCourse : courses) {
                courseMessage += singleCourse + ", ";
            }
  System.out.println(courseMessage.replaceAll(", $", ""));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM