如何打印由空格分隔n次的相同字符串

时间:2015-01-31 02:53:38

标签: java string split

我想让圣诞老人说“Ho”总共“n”次,我指定“n”。 我知道如何打印n次,但我不知道如何在“Ho”之间正确插入分隔符,结果如下:“Ho Ho Ho”

我对此进行编码的尝试如下:

public class Main
{
    public static String repeat(String str, int times) {
        return new String(new char[times]).replace("\0", str);
    }
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        String Ho="Ho";
        int n=s.nextInt();
        System.out.println(repeat(Ho, n)+"!");
    }
}

2 个答案:

答案 0 :(得分:2)

使用StringJoiner空格作为分隔符。

StringJoiner sj = new StringJoiner(" ");
String str = "Ho";
int n = 3;
for (int i = 0; i<n; i++){
    sj.add(str);
}
String text = sj.toString();
System.out.println(text); //Ho Ho Ho

您还可以使用StringJoiner(delimiter, prefix, suffix)在联接字符串末尾自动添加!(作为后缀);

StringJoiner sj = new StringJoiner(" ","","!");

答案 1 :(得分:0)

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String ho = "Ho";
        int n = s.nextInt();
        System.out.println(repeat(ho, n) + "!");
    }

    public static String repeat(String str, int times) {
        StringBuilder builder=new StringBuilder();
        for(int i=0 ; i<times ; i++){
            builder.append(str).append(" ");
        }
        return builder.toString().trim();
    }
}