3

I want to build a string which contains the number of "a" based on the a runtime variable i.For example if the value of i is 3 value of string would be "aaa" if the value of i is 5 string would be "aaaaa".how can i create it in java [ without the obvious way of creating a stringbuffer in a loop] for example in python i can just do string = 'a' * i.

Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
  • 1
    There is no such shortcut in Java. – nhahtdh Jun 21 '12 at 05:42
  • Possible Duplicate : http://stackoverflow.com/questions/2255500/can-i-multiply-strings-in-java-to-repeat-sequences – TJ- Jun 21 '12 at 05:42
  • Also possible duplicate of this http://stackoverflow.com/questions/2306235/java-repeat-character which seems to provide an answer closer to what this user is asking. – JRSofty Jun 21 '12 at 06:11

2 Answers2

3

Using Google Guava we can do his with repeat method:

public static String repeat(String string,int count)

Returns a string consisting of a specific number of concatenated copies of an input string. For example, repeat("hey", 3) returns the string "heyheyhey".

codaddict
  • 445,704
  • 82
  • 492
  • 529
1
char [] a = new char[5];
Arrays.fill(a, 'f');
Siva Tumma
  • 1,695
  • 12
  • 23