可以使用单个重复字符将 Java 字符串初始化为特定长度吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1900477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can one initialise a Java String with a single repeated character to a specific length
提问by Ron Tuffin
I'd like to create a function that has the following signature:
我想创建一个具有以下签名的函数:
public String createString(int length, char ch)
It should return a string of repeating characters of the specified length.
For example if length is 5 and ch is 'p' the return value should be:
它应该返回一串指定长度的重复字符。
例如,如果长度为 5 且 ch 为“p”,则返回值应为:
ppppp
公私伙伴关系
Is there a way to do this without looping until it is the required length?
And without any externally defined constants?
有没有办法在不循环的情况下做到这一点,直到达到所需的长度?
并且没有任何外部定义的常量?
采纳答案by Joel Shemtov
char[] chars = new char[len];
Arrays.fill(chars, ch);
String s = new String(chars);
回答by Bozho
StringUtils.repeat(str, count)
from apache commons-lang
StringUtils.repeat(str, count)
来自 apache commons-lang
回答by T.Gounelle
For the record, with Java8 you can do that with streams:
作为记录,使用 Java8,您可以使用流来做到这一点:
String p10times = IntStream.range(0, 10)
.mapToObj(x -> "p")
.collect(Collectors.joining());
But this seems somewhat overkill.
但这似乎有些矫枉过正。
回答by Mike B.
Here is an elegant, pure Java, one-line solution:
这是一个优雅的纯 Java 单行解决方案:
Java 1.5+:
Java 1.5+:
String str = new String(new char[5]).replace("String str = "p".repeat(5); // "ppppp"
", "p"); // "ppppp"
Java 11+:
Java 11+:
public static String repeat(int len, String ch) {
String s = IntStream.generate(() -> 1).limit(len).mapToObj(x -> ch).collect(Collectors.joining());
System.out.println("s " + s);
return s;
}
回答by Sohan
Bit more advance and readable ,
更先进和可读,
##代码##