* for strings in Java

Python has a * operator for strings, I'm not sure what it called, but it does this:

 >>> "h" * 9 "hhhhhhhhh" 

Is there a statement in Java such as Python * ?

+4
source share
6 answers

Many libraries have such utilities.

eg. Guava :

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

or Apache Commons / Lang :

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

Both of these classes also have methods for placing the beginning of a line or ending a specific length with a given character.

+9
source

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"; } 
+5
source

you can use something like this:

 String str = "abc"; String repeated = StringUtils.repeat(str, 3); repeated.equals("abcabcabc"); 
+3
source

There is no such operator in Java, but you can use Arrays.fill () or Apache Commons StringUtils.repeat () to achieve this 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); 
+2
source
  • represented by a replay operator

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

+1
source

There is no such operator, but you can assign sting "h" to a variable and use the for loop to print the variable as many times as you like.

0
source

Source: https://habr.com/ru/post/1483343/


All Articles