如何在java中重复字符串“n”次?
我想能够“n”次重复一串文字:
像这样的东西 –
字符串“X”, 用户输入= n, 5 = n, 输出:XXXXX
我希望这是有道理的…(请尽可能具体)
str2 = new String(new char[10]).replace("\0", "hello");
注意:这个答案最初由user102008发布: 在java中重复String的简单方法
要重复字符串n次,我们在Apache commons的Stringutils类中有一个重复方法。在重复方法中,我们可以给出字符串和字符串重复的次数以及分隔重复字符串的分隔符。
例如: StringUtils.repeat("Hello"," ",2);
返回“Hello Hello”
在上面的例子中,我们重复Hello字符串两次,空格作为分隔符。 我们可以在3个参数中给出n次,在第二个参数中给出任何分隔符。
点击此处查看完整示例
一个简单的循环将完成这项工作:
int n = 10; String in = "foo"; String result = ""; for (int i = 0; i < n; i += 1) { result += in; }
或者对于较大的字符串或更高的n
值:
int n = 100; String in = "foobarbaz"; // the parameter to StringBuilder is optional, but it's more optimal to tell it // how much memory to preallocate for the string you're about to built with it. StringBuilder b = new StringBuilder(n * in.length()); for (int i = 0; i < n; i += 1) { b.append(in); } String result = b.toString();