栅栏问题的优雅解决方案(带字符串) [英] Elegant Solutions to the Fencepost Problem (with Strings)

查看:30
本文介绍了栅栏问题的优雅解决方案(带字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指的是将Strings与中间的某个String连接起来,比如连接用句号分隔的句子,或者用逗号连接参数列表.我知道您可以使用库,但有时这些库不能满足您的要求,例如当您想要生成要连接的短语时.到目前为止,我想出了两个解决方案,

What I'm referring to is concatenating Strings 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 = ". ";
}

遭受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.

推荐答案

有一个Apache Commons Lang 中的函数系列.

如果非要自己写代码,我通常做这种事情的方式如下:

If you have to code it yourself, the way I usually do this sort of thing is as follows:

StringBuilder sb = new StringBuilder();
for (String sentence : sentences) {
    if (sb.length() != 0) {
        sb.append(". ");
    }
    sb.append(sentence);
}

这个版本允许 sentences 是任何可迭代的(返回字符串).还要注意使用 StringBuilder 而不是 StringBuffer.

This version permits sentences to be any iterable (returning strings). Also note the use of StringBuilder instead of StringBuffer.

很容易将其概括为类似于 org.apache.commons.lang.StringUtils.join 的内容.

It is easy to generalize this to something akin to org.apache.commons.lang.StringUtils.join.

这篇关于栅栏问题的优雅解决方案(带字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆