RaagaSudha
RaagaSudha

Reputation: 397

How to split the array values and store in a string in android?

I am getting the values from arraylist arr and storing those values in a string with comma separator. But for the last value also comma is adding. How can I remove that? Please help me...

My Code:

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


            }

Upvotes: 0

Views: 4876

Answers (7)

Android Guru
Android Guru

Reputation: 1

You have to pass array list to this function. it will return comma separated values.

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);
}

Upvotes: 0

pablisco
pablisco

Reputation: 14237

What about this:

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

Upvotes: 1

dreamcoder
dreamcoder

Reputation: 1253

add one condition in for loop

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

}

Upvotes: 0

Prasham
Prasham

Reputation: 6686

You can always write like this.

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);
        }

Upvotes: 0

FUBUs
FUBUs

Reputation: 617

If you try this, I think is should work.

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


            }

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

Do not add it at all:

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);
}

Upvotes: 1

ariefbayu
ariefbayu

Reputation: 21979

Try:

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

Upvotes: 0

Related Questions