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

how to print the same string separated by space n times

我想让圣诞老人说 "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("[=11=]", 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)+"!");
    }
}

自 Java 11

我们可以使用String#repeat​(int count)。有了它,您的代码可以看起来像

int n = 3;
System.out.println("Ho" + " Ho".repeat(n-1) + "!");
//output: Ho Ho Ho!

因为 Java 8

我们可以使用 StringJoiner 和 space 作为分隔符。

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(" ","","!");
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();
    }
}