创建一个包含 n 个字符的字符串
Java中有没有办法创建一个具有指定数量指定字符的字符串?就我而言,我需要创建一个包含十个空格的字符串。我当前的代码是:
final StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
outputBuffer.append(" ");
}
return outputBuffer.toString();
有更好的方法来完成同样的事情吗?特别是,我想要一些快速的东西(就执行而言)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(27)
可能是使用
String
API 的最短代码,仅:作为一种方法,无需直接实例化
char
:使用以下方式调用:
Likely the shortest code using the
String
API, exclusively:As a method, without directly instantiating
char
:Invoke using:
我强烈建议不要手工编写循环。
在您的编程生涯中,您将一遍又一遍地这样做。
阅读你的代码的人(包括你)总是必须投入时间,即使只是几秒钟,来消化循环的含义。
相反,重用提供代码的可用库之一可以实现类似 Apache Commons Lang:
这样你也不必担心性能,因此
StringBuilder
、编译器优化等的所有细节都可以解决。隐。如果该函数变得很慢,那么这将是库的一个错误。
使用 Java 11 变得更加容易:
I highly suggest not to write the loop by hand.
You will do that over and over again during the course of your programming career.
People reading your code - that includes you - always have to invest time, even if it are just some seconds, to digest the meaning of the loop.
Instead reuse one of the available libraries providing code that does just that like
StringUtils.repeat
from Apache Commons Lang:That way you also do not have to bother about performance, thus all the gory details of
StringBuilder
, Compiler optimisations etc. are hidden.If the function would turn out as slow it would be a bug of the library.
With Java 11 it becomes even easier:
嗯,现在我想了一下,也许
Arrays.fill
:当然,我假设
fill
方法与您的代码执行相同的操作,因此它可能会执行大约一样的,但至少这样少了几行。Hmm now that I think about it, maybe
Arrays.fill
: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.自 Java 11 起:
自 Java 8 起:
其中:
since Java 11:
since Java 8:
where:
for循环将被编译器优化。在像您这样的情况下,您不需要自己关心优化。相信编译器。
顺便说一句,如果有办法创建一个包含 n 个空格字符的字符串,那么它的编码方式与您刚才所做的相同。
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.
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.
在 Java 8 中,您可以使用 String.join:
In Java 8 you can use
String.join
:从 Java 11 开始,您可以简单地使用
String.repeat(count)
来解决您的问题。因此,您的代码将如下所示,而不是循环:
Since Java 11 you can simply use
String.repeat(count)
to solve your problem.So instead of a loop your code would just look like this:
如果你只想要空格,那么怎么样:
这将导致abs(n)空格;
If you want only spaces, then how about:
which will result in abs(n) spaces;
我认为这是可能的更少的代码,它使用 Guava Joiner 类:
I think this is the less code it's possible, it uses Guava Joiner class:
您可以使用标准
String.format
函数来生成N个空格。例如:
创建一个包含 5 个空格的字符串。
或
生成一串 15 个空格键。
如果您希望另一个符号重复,则必须用所需的符号替换空格:
输出:
You can use standard
String.format
function for generate N spaces.For example:
Makes a string with 5 spaces.
or
Makes a string of 15 spacebars.
If you want another symbol to repeat, you must replace spaces with your desired symbol:
Output:
我的贡献基于快速求幂算法。
我针对其他两种方法测试了该算法:
String.concat()
的常规 for 循环来连接字符串StringBuilder
的常规 for 循环测试代码(使用 for 循环和
String.concat()
对于较大的n
来说会变慢,所以我在第五次迭代后将其排除在外)。结果:
结论:
n
- 使用递归方法n
- for循环具有足够的速度My contribution based on the algorithm for fast exponentiation.
I tested the algorithm against two other approaches:
String.concat()
to concatenate stringStringBuilder
Test code (concatenation using a for loop and
String.concat()
becomes to slow for largen
, so I left it out after the 5th iteration).Results:
Conclusion:
n
- use the recursive approachn
- for loop has sufficient speed这个怎么样?
How about this?
考虑到我们有:
Java 8(使用 Stream)
Java 8(使用 nCopies)
Considering we have:
Java 8 (Using Stream)
Java 8 (Using nCopies)
使用 StringUtils:
StringUtils.repeat(' ', 10)
Use StringUtils:
StringUtils.repeat(' ', 10)
Guava 的最短解决方案:
通过 在 java 中重复字符串的简单方法< /a>.
The shortest solution with Guava:
Via Simple way to repeat a String in java.
这对我来说是有效的,无需在 Java 8 中使用任何外部库,
输出是
This worked out for me without using any external libraries in Java 8
And the output is
RandomStringUtils可以根据给定的输入大小创建字符串。
无法评论速度,但它是单班轮。
创建一个输出
如果您不想在代码中看到 \0,则
RandomStringUtils has a provision to create a string from given input size.
Cant comment on the speed, but its a one liner.
creates an output
preferable if you dont want to see \0 in your code.
整数 c = 10;
字符串空格 = String.format("%" +c+ "c", ' ');
这将解决你的问题。
int c = 10;
String spaces = String.format("%" +c+ "c", ' ');
this will solve your problem.
在大多数情况下,您只需要达到一定长度的字符串,例如 100 个空格。您可以准备一个字符串数组,其中索引号等于填充空格的字符串的大小,并查找该字符串(如果所需的长度在限制内),或者根据需要创建它(如果它在边界之外)。
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.
为了获得良好的性能,请结合 aznilamir 和 FrusteratedWithFormsDesigner
根据您的要求调整
BLANKS
的大小。我的特定BLANKS
字符串长度约为 200 个字符。For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner
Adjust size of
BLANKS
depending on your requirements. My specificBLANKS
string is about 200 characters length.只需将 StringBuffer 替换为 StringBuilder。很难打败它。
如果你的长度很大,你可能会实现一些更有效的
(但更笨拙)自追加,在每次迭代中复制长度:
另外,您可以尝试 Arrays.fill() 方法(FrusteratedWithFormsDesigner 的答案)。
Just replace your StringBuffer with a StringBuilder. Hard to beat that.
If your length is a big number, you might implement some more efficient
(but more clumsy) self-appendding, duplicating the length in each iteration:
Also, you might try the
Arrays.fill()
aproach (FrustratedWithFormsDesigner's answer).您可以将
StringBuffer
替换为StringBuilder
(后者不同步,在单线程应用程序中可能更快)并且您可以创建
StringBuilder
实例一次,而不是每次需要时创建它。像这样的事情:
并像这样使用它:
如果将
createA
作为实例变量,则可以节省创建实例的时间。这不是线程安全的,如果你有多个线程,每个线程应该有自己的副本。
You can replace
StringBuffer
withStringBuilder
( the latter is not synchronized, may be a faster in a single thread app )And you can create the
StringBuilder
instance once, instead of creating it each time you need it.Something like this:
And use it like this:
If you hold your
createA
as a instance variable, you may save time creating instances.This is not thread safe, if you have multi threads, each thread should have its own copy.
有一个这样的方法。这会在给定
String
末尾附加所需的空格,以使给定String
的长度达到特定长度。Have a method like this. This appends required spaces at the end of the given
String
to make a givenString
to length of specific length.希望字符串具有固定大小,因此您可以填充或截断,以将数据制成表格...
优秀参考 这里。
Want String to be of fixed size, so you either pad or truncate, for tabulating data...
Excellent reference here.
也可以使用如下简单方法
A simple method like below can also be used
这个怎么样?
编辑:我编写了一个简单的代码来测试这个概念,这里是我发现的。
方法 1:在循环中添加单个空格:
方法 2:追加 100 个空格并循环,然后子字符串:
我得到的结果创建了 12,345,678 个空格:
对于 10,000,000 个空格:
将直接分配和迭代相结合总是需要更少的时间,平均少 60 毫秒创造巨大的空间。对于较小的尺寸,这两个结果都可以忽略不计。
但请继续发表评论:-)
how about this?
EDIT: I've written a simple code to test the concept and here what i found.
Method 1: adding single space in a loop:
Method 2: append 100 spaces and loop, then substring:
The result I get creating 12,345,678 spaces:
and for 10,000,000 spaces:
combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.
But please continue to comment :-)
我知道没有内置方法可以满足您的要求。但是,对于像 10 这样的小固定长度,您的方法应该足够快。
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.