通过简单的Java程序,学习重复给定字符串N次,以产生包含所有重复的新字符串。我们将使用方法 Sting.repeat(N)(因为 Java 11 )并使用常规方法该表达式可用于 Java 10 。
String.repeat()
此方法返回一个字符串,该字符串的值是给定字符串的重复 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