为了账号安全,请及时绑定邮箱和手机立即绑定

Java 11 – String.repeat()介绍

标签:
Java

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

程序输出。

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

程序输出。

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

程序输出。

AbcAbcAbc


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
PHP开发工程师
手记
粉丝
8
获赞与收藏
17

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消