Java11 - String.repeat()

Java11 - String.repeat() 首页 / Java入门教程 / Java11 - String.repeat()

通过简单的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) );
	}
}

程序输出。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/java/java11-repeat-string-n-times.html

来源:LearnFk无涯教程网

AbcAbcAbc

匹配重复字符串

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

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

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);
	}
}

程序输出。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/java/java11-repeat-string-n-times.html

来源:LearnFk无涯教程网

AbcAbcAbc

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);
	}
}

程序输出。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/java/java11-repeat-string-n-times.html

来源:LearnFk无涯教程网

AbcAbcAbc

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Python -〔尹会生〕

SQL必知必会 -〔陈旸〕

从0打造音视频直播系统 -〔李超〕

消息队列高手课 -〔李玥〕

后端存储实战课 -〔李玥〕

如何成为学习高手 -〔高冷冷〕

零基础入门Spark -〔吴磊〕

现代React Web开发实战 -〔宋一玮〕

深入浅出可观测性 -〔翁一磊〕

好记忆不如烂笔头。留下您的足迹吧 :)