通过简单的Java程序,学习重复给定字符串N次,以产生包含所有重复的新字符串。我们将使用方法 Sting.repeat(N)(因为 Java 11 )并使用常规方法该表达式可用于 Java 10 。
此方法返回一个字符串,该字符串的值是给定字符串的重复 count 次的串联。如果字符串为空或 count 为零,则返回空字符串。
/** * Parameters: * count - number of times to repeat * * Returns: * A string composed of this string repeated count times or the empty string if this string is empty or count is zero * * Throws: * IllegalArgumentException - if the count is negative. */ public String repeat(int count)
Java程序将字符串" Abc"重复3次。
public class Main
{
public static void main(String[] args)
{
String str = "Abc";
System.out.println( str.repeat(3) );
}
}
程序输出。
AbcAbcAbc
如果您正在使用JDK
Java程序将字符串" Abc"重复3次。
public class Main
{
public static void main(String[] args)
{
String str = "Abc";
String repeated = new String(new char[3]).replace("
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1070/viewspace-2797666/ ,如需转载,请注明出处,否则将追究法律责任。