Java 创建一个包含 n 个字符的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2804827/
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
Create a string with n characters
提问by C. Ross
Is there a way in java to create a string with a specified number of a specified character? In my case, I would need to create a string with 10 spaces. My current code is:
java中有没有办法创建具有指定数量的指定字符的字符串?就我而言,我需要创建一个包含 10 个空格的字符串。我目前的代码是:
StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
outputBuffer.append(" ");
}
return outputBuffer.toString();
Is there a better way to accomplish the same thing. In particular I'd like something that is fast (in terms of execution).
有没有更好的方法来完成同样的事情。特别是我想要快速的东西(在执行方面)。
采纳答案by kalkin
The for loop will be optimized by the compiler. In such cases like yours you don't need to care about optimization on your own. Trust the compiler.
for 循环将由编译器优化。在像您这样的情况下,您不需要自己关心优化。相信编译器。
BTW, if there is a way to create a string with n space characters, than it's coded the same way like you just did.
顺便说一句,如果有一种方法可以创建一个包含 n 个空格字符的字符串,那么它的编码方式与您刚才所做的相同。
回答by Pops
I know of no built-in method for what you're asking about. However, for a small fixed length like 10, your method should be plenty fast.
我不知道您要问什么的内置方法。但是,对于像 10 这样小的固定长度,您的方法应该足够快。
回答by FrustratedWithFormsDesigner
Hmm now that I think about it, maybe Arrays.fill
:
嗯,现在我想想,也许Arrays.fill
:
char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
Of course, I assume that the fill
method does the same thing as your code, so it will probably perform about the same, but at least this is fewer lines.
当然,我假设该fill
方法与您的代码执行相同的操作,因此它的执行可能大致相同,但至少这是更少的行。
回答by leonbloy
Just replace your StringBuffer with a StringBuilder. Hard to beat that.
只需用 StringBuilder 替换您的StringBuffer。很难打败它。
If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:
如果您的长度是一个很大的数字,您可能会实现一些更有效(但更笨拙)的自附加,在每次迭代中复制长度:
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();
}
Also, you might try the Arrays.fill()
aproach (FrustratedWithFormsDesigner's answer).
此外,您可以尝试这种方法Arrays.fill()
(FrustratedWithFormsDesigner的答案)。
回答by OscarRyz
You can replace StringBuffer
with StringBuilder
( the latter is not synchronized, may be a faster in a single thread app )
您可以替换StringBuffer
为StringBuilder
(后者不同步,在单线程应用中可能会更快)
And you can create the StringBuilder
instance once, instead of creating it each time you need it.
并且您可以创建StringBuilder
一次实例,而不是每次需要时都创建它。
Something like this:
像这样的东西:
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;
}
}
And use it like this:
并像这样使用它:
BuildString createA = new BuildString();
String empty = createA.stringOf( ' ', 10 );
If you hold your createA
as a instance variable, you may save time creating instances.
如果你把你的createA
作为一个实例变量,你可以节省创建实例的时间。
This is not thread safe, if you have multi threads, each thread should have its own copy.
这不是线程安全的,如果您有多线程,则每个线程都应该有自己的副本。
回答by Andreas Dolk
In most cases you only need Strings upto a certains length, say 100 spaces. You could prepare an array of Strings where the index number is equal to the size of the space-filled string and lookup the string, if the required length is within the limits or create it on demand if it's outside the boundary.
在大多数情况下,您只需要达到特定长度的字符串,比如 100 个空格。您可以准备一个字符串数组,其中索引号等于填充空格的字符串的大小,并查找字符串,如果所需长度在限制范围内,或者如果超出边界,则按需创建它。
回答by Martijn Courteaux
How about this?
这个怎么样?
char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);
回答by polygenelubricants
Likely the shortest code using the String
API, exclusively:
可能是使用String
API的最短代码,专门:
String space10 = new String(new char[10]).replace('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( 'System.out.printf( "[%s]%n", spaces( 10 ) );
', ' ' );
}
', ' ');
System.out.println("[" + space10 + "]");
// prints "[ ]"
As a method, without directly instantiating char
:
作为一种方法,无需直接实例化char
:
public String fillSpaces(int len) {
/* the spaces string should contain spaces exceeding the max needed */
String spaces = " ";
return spaces.substring(0,len);
}
Invoke using:
调用使用:
public String execLoopSingleSpace(int len){
StringBuilder sb = new StringBuilder();
for(int i=0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
回答by aznilamir
how about this?
这个怎么样?
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);
}
EDIT: I've written a simple code to test the concept and here what i found.
编辑:我写了一个简单的代码来测试这个概念和我发现的内容。
Method 1: adding single space in a loop:
方法 1:在循环中添加单个空格:
C:\docs\Projects> java FillSpace 12345678
method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
Process java exited with code 0
Method 2: append 100 spaces and loop, then substring:
方法2:追加100个空格并循环,然后子串:
C:\docs\Projects> java FillSpace 10000000
method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
Process java exited with code 0
The result I get creating 12,345,678 spaces:
我得到的结果是创建了 12,345,678 个空格:
String spaces = (n==0)?"":String.format("%"+n+"s", "");
and for 10,000,000 spaces:
对于 10,000,000 个空间:
##代码##combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.
结合直接分配和迭代总是花费更少的时间,在创建巨大空间时平均减少 60 毫秒。对于较小的尺寸,这两个结果都可以忽略不计。
But please continue to comment :-)
但请继续评论:-)
回答by BryceCicada
If you want only spaces, then how about:
如果您只想要空格,那么如何:
##代码##which will result in abs(n) spaces;
这将导致 abs(n) 空格;