本文介绍了从ArrayList创建格式化的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

    ArrayList<Integer> aList = new ArrayList<Integer>();
    aList.add(2134);
    aList.add(3423);
    aList.add(4234);
    aList.add(343);

    String tmpString = "(";

    for(int aValue : aList) {
        tmpString += aValue + ",";
    }
    tmpString = (String) tmpString.subSequence(0, tmpString.length()-1) + ")";

    System.out.println(tmpString);

我的结果是预期的(2134,3423,4234,343).

My result here is (2134,3423,4234,343) as expected..

我确实将最后一个逗号替换为)以得到预期的结果.通常有更好的方法吗?

I do replace the last comma with the ending ) to get expected result. Is there a better way of doing this in general?

推荐答案

您可以使用:

String tmpString = "(" + StringUtils.join(aList, ",") + ")";

或者,如果您不能使用外部库:

Alternatively, if you can't use external libraries:

StringBuilder builder = new StringBuilder("(");
for (int aValue : aList) builder.append(aValue).append(",");
if (aList.size() > 0) builder.deleteCharAt(builder.length() - 1);
builder.append(")");
String tmpString = builder.toString();

这篇关于从ArrayList创建格式化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:16