Following is my scenario, though I have achieved the desired output but I want it to be a decent and optimized code.
String arr[]={"we","er","rtt","yu","uu","ii"};
StringBuilder strcat = new StringBuilder();
for(int i1=0;i1<arr.length;i1++)
{
// Some processing
strcat.append(arr[i1]);
if(arr.length-1!=i1)
{
strcat.append(",");
}
}
System.out.println("Value:"+strcat);
I have String[]
array and some processing, after processing I want to append the values with comma(,
).
the problem is comma , it appends to last values also, that I don’t want, I have applied a logic. I don’t know whether it is correct.but output is correct.Please do correct me if I am wrong and do suggest if it has any other means to achieve.
Nice trick I learned here
String SEPARATOR = "";
for(int i1=0;i1<arr.length;i1++)
{
// Some processing
strcat.append(SEPARATOR);
strcat.append(arr[i1]);
SEPARATOR = ",";
}
If you're using Java 8, there's already support for this in the String class
String result = String.join(",", arr);
will result in
"we,er,rtt,yu,uu,ii"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With