Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one initialize a Java string with a single repeated character to a specific length [duplicate]

I'd like to create a function that has the following signature:

public String createString(int length, char ch) 

It should return a string of repeating characters of the specified length.
For example if length is 5 and ch is 'p' the return value should be:

ppppp

Is there a way to do this without looping until it is the required length?
And without any externally defined constants?

like image 787
Ron Tuffin Avatar asked Dec 14 '09 11:12

Ron Tuffin


People also ask

How do you repeat a single character in Java?

Here is the shortest version (Java 1.5+ required): repeated = new String(new char[n]). replace("\0", s); Where n is the number of times you want to repeat the string and s is the string to repeat.

How do you repeat a character in a string in Java?

Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);

How do you declare a string of a specific size in Java?

To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];


2 Answers

char[] chars = new char[len]; Arrays.fill(chars, ch); String s = new String(chars); 
like image 54
Joel Shemtov Avatar answered Sep 19 '22 13:09

Joel Shemtov


StringUtils.repeat(str, count) from apache commons-lang

like image 34
Bozho Avatar answered Sep 22 '22 13:09

Bozho