Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending with StringBuilder

I have 5 checkboxes and I have to select multiple checkboxes.

I made a code like this to check check box is checked:

sports=(CheckBox)findViewById(R.id.sports_btn);
sports.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (sports.isChecked() == true)
        list.add("4");
    }
}); 

I am adding a value to an array list:

list ArrayList<String> list = new ArrayList<String>();

and I am retrieving the value as string like this:

StringBuilder sb = new StringBuilder();
for(int  i =0; i < list.size(); i++)
{
    for (String str: list)
    {  
        sb.append(str.toString());
        sb.append(",");
    }

}
String sel_cat = sb;

I am getting the string but if two values are selected it is coming like 2,3, How to remove that last comma? I don't want the last comma the string has to be like 2,3.

like image 311
Froyo Avatar asked Nov 17 '11 12:11

Froyo


People also ask

What is append in StringBuilder?

append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.

What is append () in Java?

Append in Java is a StringBuilder and StringBuffer class method used to append a value to the current sequence. String concatenation in Java is done using the StringBuilder or StringBuffer class and append() method.

How many times is the StringBuilder append method overloaded?

Append() in StringBuilder and StringBuffer There are 13 various overloaded append() methods in both StringBuffer and StringBuilder classes.


1 Answers

StringBuilder sb = new StringBuilder();
sb.deleteCharAt(sb.length()-1) 

Or in your code, use

StringBuilder sb = new StringBuilder();

for(int  i =0;i<list.size();i++)
{
    String prefix = "";
    for (String str : list)
    { 
        sb.append(prefix);
        prefix = ",";
        sb.append(str);  
    }
}

String sel_cat = sb;
like image 91
user370305 Avatar answered Oct 14 '22 02:10

user370305