[英]how to print the same string separated by space n times
I want to make Santa Claus say "Ho" a total of "n" times, where I specify "n".我想让圣诞老人说“Ho”总共“n”次,我指定了“n”。 I know how to print it n times, but I don't know how to properly insert a separator between the "Ho"s, such that the result looks like: "Ho Ho Ho"我知道如何打印 n 次,但我不知道如何在“Ho”之间正确插入分隔符,使结果看起来像:“Ho Ho Ho”
My attempt at coding this up is given below:我对此进行编码的尝试如下:
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)+"!");
}
}
We can use String#repeat(int count)
.我们可以使用String#repeat(int count)
。 With it your code can look like有了它你的代码看起来像
int n = 3;
System.out.println("Ho" + " Ho".repeat(n-1) + "!");
//output: Ho Ho Ho!
We can use StringJoiner with space as delimiter.我们可以使用带有空格作为分隔符的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
You can also use StringJoiner(delimiter, prefix, suffix) to automatically add !
您还可以使用StringJoiner(delimiter, prefix, suffix)自动添加!
at the end of joined strings (as 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.