如何将自定义字符数附加到字符串?

时间:2013-12-08 22:05:51

标签: java string

如何在不使用任何循环的字符串变量数量的自定义字符中添加自定义位置?什么是最有效的方式?

if(s.length() < width) {  //add spaces
            n = width - s.length();
            s = (' '*n ) + s; // pseudo code
       }

1 个答案:

答案 0 :(得分:1)

试试这样:

String repeated = new String(new char[n]).replace("\0", yourChar);
String s = input.substring(0, x) + repeated + input.substring(x+1);

其中n是您希望重复字符串yourChar的次数(也可能长于一个字符)

来自:Link