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.
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.
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, '. ')
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.
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.
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);
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With