Mohamed Nagy Mohamed Nagy - 18 days ago 9
Java Question

Convert array of Strings to String

Hello i have a little problem with array conversion

i want to convert this array format

["x","z","y"]
To this String Format
('x','y','z')
with commas and parentheses.

btw this array is dynamic in size may be increased or decreased

this is my try

public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String [] arr = {"x","y","z"};
String s = "(";

for(int i = 0; i <arr.length;i++){
s +="'".concat(arr[i]).concat("'") + ',' ;
if(i == arr.length-1)
s.replace(',', ')');
}

System.out.print(s);

}


this is my output ('x','y','z',
i want to replace the last comma with ')'

Answer

This also will do the magic..

Please use StringBuilder for these kind of string operations..

for (int i = 0; i < arr.length; i++) {
            s += "'".concat(arr[i]).concat("'") + ',';
        }

        s = s.concat(")");

        System.out.print(s.replace(",)", ")"));
Comments