Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize string dynamically in java

Tags:

java

string

I want to initialize a string as follows:

public int function (  int count )  { 
String s_new = "88888...  'count' number of 8's "    <-- How to do this
//Other code 
}

Currently I'm not sure how to do this, so I've declared an int array ( int[] s_new ) instead and Im using for loops to initialize this int array.

EDIT: I meant that I need to initialize a string containing only 8's ... the number of times the digit 8 occurs is 'count' times.

like image 499
Nikhil Avatar asked Jan 22 '26 09:01

Nikhil


2 Answers

You can use Guava's Strings.repeat() method:

String str = Strings.repeat("8", count);
like image 165
Rohit Jain Avatar answered Jan 23 '26 21:01

Rohit Jain


In these cases, it is recommended to use a StringBuilder:

StringBuilder sb = new StringBuilder();
String s = "";
int count = 8;

for (int i = 0; i < count; i++) {
    sb.append('8');
}

s = sb.toString();

System.out.println(s);

Output:

88888888
like image 36
Christian Tapia Avatar answered Jan 23 '26 22:01

Christian Tapia