Java 11 – 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) );
	}
}

程序輸出。

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

鏈接:https://www.learnfk.com/article-java11-repeat-string-n-times
來源:Learnfk無涯教程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM