java - Based on the condition how to create StringBuffers and append data to it -
my arraylist contains list of values in string format
the data inside arraylist way
arraylist<string> my_list = new arraylist<string>(); my_list.add("today date"); my_list.add("some content1"); my_list.add("*****"); my_list.add("some content2"); my_list.add("some content3"); my_list.add("*****"); my_list.add("some content5"); my_list.add("some content6"); my_list.add("*****"); my_list.add("some content8");
i trying create 1 sepearte stringbuffer content present after seperator *****
i have tried way
import java.io.filenotfoundexception; import java.util.arraylist; import org.json.jsonarray; public class test { public static void main(string[] args) throws filenotfoundexception { arraylist<string> my_list = new arraylist<string>(); jsonarray jsarray = new jsonarray(); my_list.add("today date"); my_list.add("some content1"); my_list.add("*****"); my_list.add("some content2"); my_list.add("some content3"); my_list.add("*****"); my_list.add("some content5"); my_list.add("some content6"); my_list.add("*****"); my_list.add("some content8"); for(int i=0;i<my_list.size();i++) { string linedata = my_list.get(i); if(linedata.equals("*****")) { stringbuffer sb = new stringbuffer(); sb.append(linedata); jsarray.put(sb.tostring()); } } system.out.println(jsarray); } }
the output got
["*****","*****","*****"]
where expected output should way
["today date content1", "some content2 content3", "some content5 content6", "some content8"]
could please tell me making mistake , how resolve
you doing exact opposite of intent; ignoring content , adding "*****" separators. incidentally, if don't need thread safe here, can use stringbuilder
instead of stringbuffer
.
instead of creating stringbuilder
every time encounter separator, need have stringbuilder
created , ready before encounter separator. if encounter separator, don't append it; convert string, place in array, , clear it. make sure place last string in array after loop finished, after last separator.
stringbuilder sb = new stringbuilder(); for(int i=0;i<my_list.size();i++) { string linedata = my_list.get(i); if(linedata.equals("*****")) { jsarray.put(sb.tostring()); sb.setlength(0); // clear } else { sb.append(linedata); } } jsarray.put(sb.tostring()); // last one!
Comments
Post a Comment