Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create String of length consisting of same character repeated multiple times? [duplicate]

Tags:

java

If i want a String s which would consist of n instances of character A, can this be done cleaner in Java other then

public static String stringOfSize(int size, char ch) {
    StringBuilder s = new StringBuilder();
    while (size-- > 0) {
        s.append(ch);
    }
    return s.toString();
}

Can we do better? Just wondering.

like image 598
James Raitsev Avatar asked May 28 '13 19:05

James Raitsev


People also ask

How do you make a string repeating characters?

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.

How do I add a repeating character to a string in C++?

There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well: std::string(5, '. ')

How do you repeat StringUtils?

repeat() is a static method of the StringUtils class that is used to repeat a given string/character a number of times to form a new string. The method also takes a string separator that is injected each time.

How do you repeat a char 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.


2 Answers

Nothing wrong with this code at all... But maybe you can use Arrays.fill():

public static String stringOfSize(int size, char ch)
{
    final char[] array = new char[size];
    Arrays.fill(array, ch);
    return new String(array);
}
like image 190
fge Avatar answered Nov 15 '22 06:11

fge


You could do the following:

return StringUtils.repeat(ch, size);

Note: StringUtils is not built-in to the JDK - see http://commons.apache.org/proper/commons-lang/

like image 39
Justin Bicknell Avatar answered Nov 15 '22 07:11

Justin Bicknell