Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to generate a String of n repeated characters?

Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; ++i) {     sb.append(c); } String result = sb.toString(); 

Surely there is some static library function that already does this for me?

like image 515
foobar Avatar asked Aug 18 '11 12:08

foobar


People also ask

How do you make a string of repeating characters?

Common Ways to Build a String We'll iterate through a for loop N times appending the repeated character: StringBuilder builder = new StringBuilder(N); for (int i = 0; i < N; i++) { builder. append("a"); } String newString = builder. toString(); assertEquals(EXPECTED_STRING, newString);

How do you repeat a string n number?

The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.

How do you write an n character for a string in Python?

We can easily use the Python join() function to create a string of n characters.


2 Answers

int n = 10; char[] chars = new char[n]; Arrays.fill(chars, 'c'); String result = new String(chars); 

EDIT:

It's been 9 years since this answer was submitted but it still attracts some attention now and then. In the meantime Java 8 has been introduced with functional programming features. Given a char c and the desired number of repetitions count the following one-liner can do the same as above.

String result = IntStream.range(1, count).mapToObj(index -> "" + c).collect(Collectors.joining()); 

Do note however that it is slower than the array approach. It should hardly matter in any but the most demanding circumstances. Unless it's in some piece of code that will be executed thousands of times per second it won't make much difference. This can also be used with a String instead of a char to repeat it a number of times so it's a bit more flexible. No third-party libraries needed.

like image 91
G_H Avatar answered Oct 09 '22 09:10

G_H


If you can, use StringUtils from Apache Commons Lang:

StringUtils.repeat("ab", 3);  //"ababab" 
like image 41
Tomasz Nurkiewicz Avatar answered Oct 09 '22 09:10

Tomasz Nurkiewicz