0

我从 arraylist arr获取值并将这些值存储在带有逗号分隔符的字符串中。但是对于最后一个值,逗号也在添加。我怎样才能删除它?请帮我...

我的代码:

ArrayList<String> arr;  
String str;

    for (int i = 0; i < arr.size(); i++) {

                int kk = arr.size();
                System.out.println("splitting test" + arr.get(i));
                str += arr.get(i) + ",";

                System.out.println("result" + str);


            }
4

7 回答 7

1

根本不要添加它:

ArrayList<String> arr;  
String str;

for (int i = 0; i < arr.size(); i++) {
   int kk = arr.size();
   System.out.println("splitting test" + arr.get(i));
   str += arr.get(i);
   if (i + 1 != arr.size()) {
     str+= ",";
   }
   System.out.println("result" + str);
}
于 2012-04-18T09:42:37.090 回答
1

那这个呢:

StringBuilder builder = new StringBuilder();
for(Object item : arrayOrIterable) builder.append(item).append(",");
String result = builder.deleteCharAt(builder.length() - 1).toString();
于 2012-04-18T20:28:37.547 回答
0

尝试:

str.substring(0, str.length()-1);
于 2012-04-18T09:42:34.157 回答
0

如果你试试这个,我认为应该可以。

ArrayList<String> arr;  
String str;

    for (int i = 0; i < arr.size(); i++) {

                int kk = arr.size();
                System.out.println("splitting test" + arr.get(i));
                str += arr.get(i) + i!=arr.size()-1?"":",";

                System.out.println("result" + str);


            }
于 2012-04-18T09:42:48.753 回答
0

你总是可以这样写。

String str;

        for (int i = 0; i < arr.size(); i++) {

            int kk = arr.size();
            System.out.println("splitting test" + arr.get(i));
            // It is your old code str += arr.get(i) + ",";
            // Insted write like this

            str += arr.get(i);
            if (i < arr.size() - 1) {
                str += ",";
            }
            System.out.println("result" + str);
        }
于 2012-04-18T09:45:39.003 回答
0

在 for 循环中添加一个条件

if(i == arr.size()-1)
{
    str += arr.get(i);
}
else
{
   str += arr.get(i) + ",";

}
于 2012-04-18T09:45:45.437 回答
0

您必须将数组列表传递给此函数。它将返回逗号分隔的值。

public static <T> String getReasonArray(Collection<T> values) {
    if (values == null || values.isEmpty()) return "";
    StringBuilder result = new StringBuilder();
    for (T val : values) {
        result.append(val);
        result.append(",");
    }
    return result.substring(0, result.length() - 1);
}
于 2017-10-26T08:32:08.103 回答