栅栏柱问题的优雅解决方案(带字符串)
我指的是将 String
与中间的某个 String
连接起来,例如用句点分隔的句子,或用逗号连接参数列表。我知道您可以使用库,但有时这些库不能满足您的要求,例如当您想要生成要连接的短语时。到目前为止,我已经提出了两种解决方案,
StringBuffer sentence = new StringBuffer();
String period = "";
for ( int i = 0; i < sentences.length; i++ ) {
sentence.append( period + sentences[i] );
period = ". ";
}
它们都受到period
的冗余重新分配的影响。还有
StringBuffer actualParameters = new StringBuffer();
actualParameters.append( parameters[0] );
for ( int i = 1; i < parameters.length; i++ ) {
actualParameters.append( ", " + parameters[i] );
}
一种取消了重新分配,但看起来仍然没有吸引力。任何其他解决方案将不胜感激。
What I'm referring to is concatenating String
s with a certain String
in the middle, such as concatenating sentences separated by a period, or parameter lists with a comma. I know you can use libraries, but sometimes these can't do what you want, like when you want to generate the phrases you are concatenating. So far I've come up with two solutions,
StringBuffer sentence = new StringBuffer();
String period = "";
for ( int i = 0; i < sentences.length; i++ ) {
sentence.append( period + sentences[i] );
period = ". ";
}
which suffers from the redundant reassignment of period
. There is also
StringBuffer actualParameters = new StringBuffer();
actualParameters.append( parameters[0] );
for ( int i = 1; i < parameters.length; i++ ) {
actualParameters.append( ", " + parameters[i] );
}
which removes the reassignment but which still looks unappealing. Any other solutions are greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一个 Apache Commons Lang 中的一系列函数就是这样做的。
如果您必须自己编写代码,我通常执行此类操作的方式如下:
此版本允许句子是任何可迭代的(返回字符串)。另请注意使用
StringBuilder
而不是StringBuffer
。很容易将其概括为类似于 org.apache.commons.lang.StringUtils.join 的东西。
There is a family of functions in Apache Commons Lang that does just that.
If you have to code it yourself, the way I usually do this sort of thing is as follows:
This version permits
sentences
to be any iterable (returning strings). Also note the use ofStringBuilder
instead ofStringBuffer
.It is easy to generalize this to something akin to
org.apache.commons.lang.StringUtils.join
.如果您至少有一个字符串,那么:
If you have at least one string then:
似乎是一个常见问题!
删除 StringBuilder 的最后一个字符?
这会导致类似的结果:
Seems like a common question!
Remove last character of a StringBuilder?
That would lead to something like:
不要使用 StringBuffer 因为不必要的同步和“+”运算符,因为这会创建不必要的中间 String 对象。
Don't use StringBuffer because of unnecessary synchronisation and "+" operator, because this will create unnecassry intemediate String objects.