如何拆分数组值并存储在android中的字符串中?

时间:2012-04-18 09:39:43

标签: android

我从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);


            }

7 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

这个怎么样:

StringBuilder builder = new StringBuilder();
for(Object item : arrayOrIterable) builder.append(item).append(",");
String result = builder.deleteCharAt(builder.length() - 1).toString();

答案 2 :(得分:0)

尝试:

str.substring(0, str.length()-1);

答案 3 :(得分: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);


            }

答案 4 :(得分: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);
        }

答案 5 :(得分:0)

在for循环中添加一个条件

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

}

答案 6 :(得分: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);
}