从打印语句中删除最后一个分隔符 [英] Remove last separator from print statement

查看:55
本文介绍了从打印语句中删除最后一个分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种对整数数组进行排序的方法.如何从输出中删除最后一个分隔符?

Here's a method for sorting an integer array. How can I remove the last separator form the output?

public void Sort(int[] sort) {
        for (int a:sort) {
            System.out.print(a+ ", ");
        }
    }

输出

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 

期望输出

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

推荐答案

如果您使用的是 Java 8,一个非常干净的解决方案是使用新的 StringJoiner 类.此类旨在将字符串与自定义分隔符连接在一起,并且可能带有前缀/后缀.使用这个类,您无需像在代码段中那样担心删除最后一个分隔符.

If you are using Java 8, a very clean solution is using the new StringJoiner class. This class was designed to join Strings together with a custom separator, and possibly with a prefix / suffix. With this class, you don't need to worry about deleting the last separator as you do in your snippet.

public void sort(int[] sort) {
    StringJoiner sj = new StringJoiner(",");
    for (int a : sort) {
        sj.add(String.valueOf(a));
    }
    System.out.println(sj.toString());
}

您也可以删除 for 循环并使用 Streams 代替:

You could also drop the for loop and use Streams instead:

String str = Arrays.stream(sort).mapToObj(String::valueOf).collect(joining(","));

这篇关于从打印语句中删除最后一个分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆