在java中动态初始化字符串

时间:2014-01-18 20:24:35

标签: java string

我想按如下方式初始化字符串:

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

目前我不知道该怎么做,所以我已经声明了一个int数组(int [] s_new)而我使用for循环来初始化这个int数组。

编辑:我的意思是我需要初始化一个只包含8的字符串......数字8出现的次数是'count'次。

5 个答案:

答案 0 :(得分:4)

您可以使用Guava's Strings.repeat()方法:

String str = Strings.repeat("8", count);

答案 1 :(得分:3)

尝试:

String s_new = "";
for (int i = 0; i < count; i++) {
    s_new += "8";
}
return s_new;

现在,这是一个天真的解决方案。更好的解决方案(如此处的其他答案中所述)将使用StringBufferStringBuilder以更有效的方式完成此操作。

此外,进一步阅读这两个选项之间的差异:Difference between StringBuilder and StringBuffer

答案 2 :(得分:3)

在这些情况下,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);

<强>输出:

88888888

答案 3 :(得分:2)

您可以使用StringBuilder类构建字符串。

StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
    sb.append('8')
String s_new = sb.toString();
然后

s_new8 count {。}}。

答案 4 :(得分:1)

使用数组的纯Java解决方案:

public String repeat(char ch, int count) {
    char[] chars = new char[count];
    Arrays.fill(chars, ch);
    return new String(chars);
}