on It Road.com
Java 使用正则表达式重复字符串
如果我们正在使用 JDK <= 10,那么我们可以考虑使用正则表达式将字符串重复 N 次。
Java 程序将字符串 'Abc' 重复 3 次。
public class Main
{
public static void main(String[] args)
{
String str = "Abc";
String repeated = new String(new char[3]).replace("/**
* 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)
", str);
System.out.println(repeated);
}
}
Java 11 String.repeat() 方法
此方法返回一个字符串,其值是给定字符串重复“count”次的串联。
如果字符串为空或者 count为零,则返回空字符串。
语法
public class Main
{
public static void main(String[] args)
{
String str = "Abc";
System.out.println( str.repeat(3) );
}
}
例子
Java 程序将字符串 'Abc' 重复 3 次。
##代码##日期:2020-09-17 00:09:38 来源:oir作者:oir
