通过简单的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
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶(hù)
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)