4

In Python, there is a * operator for strings, I'm not sure what it's called but it does this:

>>> "h" * 9
"hhhhhhhhh"

Is there an operator in Java like Python's *?

LazySloth13
  • 2,369
  • 8
  • 28
  • 37

7 Answers7

9

Many libraries have such utility methods.

E.g. Guava:

String s = Strings.repeat("*",9);

or Apache Commons / Lang:

String s = StringUtils.repeat("*", 9);

Both of these classes also have methods to pad a String's beginning or end to a certain length with a specified character.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
5

I think the easiest way to do this in java is with a loop:

String string = "";
for(int i=0; i<9; i++)
{
    string+="h";
}
Lawrence Andrews
  • 440
  • 4
  • 12
  • 2
    Note that if you're going to do a LOT of concatenations, you should use a StringBuilder for performance. (Corollary: If it finishes in a blink of an eye, no optimization needed.) – Patashu May 29 '13 at 11:31
  • 2
    String+=String in a loop is pure evil – Sean Patrick Floyd May 29 '13 at 11:33
  • See [Effective Java by Josh Bloch](http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683), Item 51: Beware the performance of string concatenation – Sean Patrick Floyd May 29 '13 at 12:41
3

you can use something like this :

String str = "abc";
String repeated = StringUtils.repeat(str, 3);

repeated.equals("abcabcabc");
Yassering
  • 226
  • 1
  • 3
  • 11
2

There is no such operator in Java, but you can use Arrays.fill() or Apache Commons StringUtils.repeat() to achieve that result:

Assuming

    char src = 'x';
    String out;

with Arrays.fill()

    char[] arr = new char[10] ;
    Arrays.fill(arr,src);        
    out = new String(arr);

with StringUtils.repeat()

    out = StringUtils.repeat(src, 10);
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
1
  • seems to be a repeat operator

Use apache libraries (common-lang) : Stringutils.repeat(str, nb)

mlwacosmos
  • 4,391
  • 16
  • 66
  • 114
1

String.repeat(count) has been available since JDK 11. String.repeat(count)

wickund
  • 1,077
  • 9
  • 13
0

There is no operator like that, but you could assign the sting "h" to a variable and use a for loop to print the variable a desired amount of times.

Chris M
  • 13
  • 6