String.repeat() – 在 Java 中重复字符串 N 次

String.repeat() – 在 Java 中重复字符串 N 次

原文: https://howtodoinjava.com/java11/repeat-string-n-times/

通过简单的 Java 程序,学习将给定的字符串重复 N 次,以产生包含所有重复的新字符串。 我们将使用方法Sting.repeat(N)(自 Java 11 起),并使用可用于 Java 10 的正则表达式。

1. String.repeat() API(自 Java 11 起)

此方法返回一个字符串,该字符串的值是重复count次的给定字符串的连接。 如果字符串为空或count为零,则返回空字符串。

1.1 语法

/**
* 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)

1.2 示例

Java 程序将字符串"Abc"重复 3 次。

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";

		System.out.println( str.repeat(3) );
	}
}

程序输出。

AbcAbcAbc

2. 使用正则表达式重复字符串(直到 Java 10)

如果您正在使用 JDK < = 10,则可以考虑使用正则表达式将字符串重复 N 次。

Java program to repeat string ‘Abc’ to 3 times.

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";

		String repeated = new String(new char[3]).replace("\0", str);

		System.out.println(repeated);
	}
}

程序输出:

AbcAbcAbc

3. Apache Common 的StringUtils

如果不是正则表达式,则可以使用StringUtils类及其方法repeat(times)

import org.apache.commons.lang3.StringUtils;

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";

		String repeated = StringUtils.repeat(str, 3);

		System.out.println(repeated);
	}
}

程序输出:

AbcAbcAbc

向我提供有关如何在 Java 中将字符串重复 N 次的问题。

学习愉快!