Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

* for strings in Java [duplicate]

Tags:

java

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 *?

like image 322
LazySloth13 Avatar asked Dec 01 '22 03:12

LazySloth13


2 Answers

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.

like image 138
Sean Patrick Floyd Avatar answered Dec 23 '22 05:12

Sean Patrick Floyd


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";
}
like image 44
Lawrence Andrews Avatar answered Dec 23 '22 05:12

Lawrence Andrews