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.

3

2 Answers 2

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".

1
  • I guess they too use StringBuffer in a for loop internally Jun 21, 2012 at 6:07
1
char [] a = new char[5];
Arrays.fill(a, 'f');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.