java中是否有一种方法可以创建具有指定数量的指定字符的字符串?就我而言,我需要创建一个包含10个空格的字符串。我当前的代码是:
StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
outputBuffer.append(" ");
}
return outputBuffer.toString();
是否有更好的方法来完成同一件事。特别是我想快速(在执行方面)。
for循环将由编译器优化。在像您这样的情况下,您无需自己担心优化。信任编译器。 :)
编辑:顺便说一句,如果有一种方法可以创建一个包含n个空格字符的字符串,那么它的编码方式就和您刚才一样。
自Java 11起,您可以简单地使用#######
解决您的问题。
返回一个字符串,该字符串的值是此字符串的串联并重复
String.repeat(count)
次。如果此字符串为空或
String.repeat(count)
为零,则返回空字符串。
因此,不是循环,您的代码将如下所示:
count
考虑到我们有:
count
" ".repeat(length);
String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)
怎么样?
String resultOne = IntStream.range(0,n)
.mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc
String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc
规定可以根据给定的输入大小创建字符串。不能评论速度,但它是一线。
char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);
创建输出
\ t \ t \ t \ t \ t
如果您不想在代码中看到\ 0,则是首选。
使用StringUtils:StringUtils.repeat('',10)
[在大多数情况下,您只需要指定长度的字符串即可,例如100个空格。您可以准备一个字符串数组,其中索引号等于空格字符串的大小,并在所需长度在限制范围内的情况下查找该字符串,或者在边界之外按需创建它。
只需将您的StringBuffer替换为Stream.generate(() -> ch).limit(n).collect(joining());
。很难击败。
如果您的长度很大,可以实施一些更有效的方法(但更笨拙)自我附加,在每次迭代中复制长度:
import static java.util.stream.Collectors.joining;
import java.util.stream.Stream;
...
String ch = " ";
int n = 10;
Stream
.generate(() -> ch)
.limit(n)
.collect(joining());
也可以尝试使用StringBuilder方法(FrustratedWithFormsDesigner的答案)。
您可以将 public static String dummyString(char c, int len) {
if( len < 1 ) return "";
StringBuilder sb = new StringBuilder(len).append(c);
int remnant = len - sb.length();
while(remnant > 0) {
if( remnant >= sb.length() ) sb.append(sb);
else sb.append(sb.subSequence(0, remnant));
remnant = len - sb.length();
}
return sb.toString();
}
替换为Arrays.fill()
(后者不同步,在单线程应用中可能更快)
并且您可以创建一次StringBuffer
实例,而不是每次都需要创建它。
类似这样的东西:
StringBuilder
并像这样使用它:
StringBuilder
如果将class BuildString {
private final StringBuilder builder = new StringBuilder();
public String stringOf( char c , int times ) {
for( int i = 0 ; i < times ; i++ ) {
builder.append( c );
}
String result = builder.toString();
builder.delete( 0 , builder.length() -1 );
return result;
}
}
用作实例变量,则可以节省创建实例的时间。
这不是线程安全的,如果您有多个线程,则每个线程应具有自己的副本。
[为了获得良好的性能,请结合 BuildString createA = new BuildString();
String empty = createA.stringOf( ' ', 10 );
和createA
的答案
aznilamir
根据需要调整FrustratedWithFormsDesigner的大小。我的特定private static final String BLANKS = " ";
private static String getBlankLine( int length )
{
if( length <= BLANKS.length() )
{
return BLANKS.substring( 0, length );
}
else
{
char[] array = new char[ length ];
Arrays.fill( array, ' ' );
return new String( array );
}
}
字符串大约是200个字符的长度。
可能是使用String
API的最短代码,排他:
String space10 = new String(new char[10]).replace('\0', ' ');
System.out.println("[" + space10 + "]");
// prints "[ ]"
作为一种方法,不直接实例化char
:
import java.nio.CharBuffer;
/**
* Creates a string of spaces that is 'spaces' spaces long.
*
* @param spaces The number of spaces to add to the string.
*/
public String spaces( int spaces ) {
return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}
使用以下方式调用:
System.out.printf( "[%s]%n", spaces( 10 ) );
具有这样的方法。这会在给定BLANKS
的末尾附加所需的空格,以使给定BLANKS
达到特定长度的长度。
String
使用番石榴的最短解决方案:
String
通过public static String fillSpaces (String str) {
// the spaces string should contain spaces exceeding the max needed
String spaces = " ";
return str + spaces.substring(str.length());
}
。
也可以使用下面的简单方法
Strings.repeat(" ", len)
这个怎么样?
Simple way to repeat a String in java
编辑:我编写了一个简单的代码来测试这个概念以及在这里找到的东西。
方法1:在循环中添加单个空格:
public static String padString(String str, int leng,char chr) {
for (int i = str.length(); i <= leng; i++)
str += chr;
return str;
}
方法2:附加100个空格并循环,然后加上子字符串:
public String fillSpaces(int len) {
/* the spaces string should contain spaces exceeding the max needed */
String spaces = " ";
return spaces.substring(0,len);
}
我得到的创建12,345,678个空格的结果:
public String execLoopSingleSpace(int len){
StringBuilder sb = new StringBuilder();
for(int i=0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
以及10,000,000个空格:
public String execLoopHundredSpaces(int len){
StringBuilder sb = new StringBuilder(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ");
for (int i=0; i < len/100 ; i++) {
sb.append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ");
}
return sb.toString().substring(0,len);
}
将直接分配和迭代结合在一起通常会花费更少的时间,而在创建巨大空间时平均要少60ms。对于较小的尺寸,两个结果都可以忽略不计。
但请继续发表评论:-)
我不知道您要问的内置方法。但是,对于较小的固定长度(如10),您的方法应该足够快。
现在我想起来,也许是Arrays.fill
:
Arrays.fill
当然,我假设char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
方法与您的代码执行相同的操作,因此它可能会执行相同的操作,但是至少这是更少的行。
我强烈建议不要用手编写循环。您将在编程生涯中一遍又一遍地做。读取您的代码(包括您在内)的人们总是必须花时间,即使只是几秒钟,也要消化循环的含义。
代替reuse提供代码的可用库之一,其功能类似于fill
中的StringUtils.repeat
:
Apache Commons Lang
这样,您也不必担心性能,因此StringUtils.repeat(' ', length);
的所有细节,编译器优化等都被隐藏了。如果该函数的运行速度很慢,则可能是该库的错误。
StringBuilder
变得更加容易:
Java 11
在Java 8中,您可以使用" ".repeat(length);
:
String.join
如果只需要空格,那么如何:
String.join("", Collections.nCopies(n, s));
将导致abs(n)空格;
我认为这是可能的更少代码,它使用Guava Joiner类:
String spaces = (n==0)?"":String.format("%"+n+"s", "");
.on(“”)。join(Joiner(10,“”));
我基于快速求幂算法的贡献。
Collections.nCopies
我针对另外两种方法测试了该算法:
/**
* Repeats the given {@link String} n times.
*
* @param str
* the {@link String} to repeat.
* @param n
* the repetition count.
* @throws IllegalArgumentException
* when the given repetition count is smaller than zero.
* @return the given {@link String} repeated n times.
*/
public static String repeat(String str, int n) {
if (n < 0)
throw new IllegalArgumentException(
"the given repetition count is smaller than zero!");
else if (n == 0)
return "";
else if (n == 1)
return str;
else if (n % 2 == 0) {
String s = repeat(str, n / 2);
return s.concat(s);
} else
return str.concat(repeat(str, n - 1));
}
连接字符串的常规循环String.concat()
的常规for循环测试代码(对于大的StringBuilder
,使用for循环和String.concat()
的连接变慢,因此在第5次迭代后将其省略。
n
结果:
/**
* Test the string concatenation operation.
*
* @param args
*/
public static void main(String[] args) {
long startTime;
String str = " ";
int n = 1;
for (int j = 0; j < 9; ++j) {
n *= 10;
System.out.format("Performing test with n=%d\n", n);
startTime = System.currentTimeMillis();
StringUtil.repeat(str, n);
System.out
.format("\tStringUtil.repeat() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
if (j <5) {
startTime = System.currentTimeMillis();
String string = "";
for (int i = 0; i < n; ++i)
string = string.concat(str);
System.out
.format("\tString.concat() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
} else
System.out
.format("\tString.concat() concatenation performed in x milliseconds\n");
startTime = System.currentTimeMillis();
StringBuilder b = new StringBuilder();
for (int i = 0; i < n; ++i)
b.append(str);
b.toString();
System.out
.format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
}
}
结论:
Performing test with n=10
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 0 milliseconds
StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1 milliseconds
StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1 milliseconds
StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 43 milliseconds
StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1579 milliseconds
StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
StringUtil.repeat() concatenation performed in 7 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
StringUtil.repeat() concatenation performed in 80 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
StringUtil.repeat() concatenation performed in 1372 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 12125 milliseconds
-使用递归方法n
-对于循环具有足够的速度您可以使用标准的n
函数生成N个空格。例如:
String.format
使用5个空格组成字符串。
或
String.format("%5c", ' ');
制作15个空格键的字符串。
如果要重复另一个符号,则必须用所需的符号替换空格:
int count = 15;
String fifteenSpacebars = String.format("%" + count + "c", ' ');
输出:
int count = 7;
char mySymbol = '#';
System.out.println(String.format("%" + count + "c", ' ').replaceAll("\\ ", "\\" + mySymbol));