开发者

java 2dimensional array to string array

开发者 https://www.devze.com 2023-02-06 10:50 出处:网络
I have two dimensional array with values created as follows: for(int i=0;i<2;i++) { for(int j=0;j<4;j++)

I have two dimensional array with values created as follows:

for(int i=0;i<2;i++) 
{
 for(int j=0;j<4;j++)
 {
    array[i][j]=e.getValues (r,c);
 }
}

which will return :

array[0][0] => 16
array[0][1] => 11
array[0][2] => 7
array[0][3] => 6
array[1][0] => 10
array[1][1] => 7
array[1][2] => 6
array[1][3] => 6

how can i store these values as a single string in another 2d string array:

arrayValues[0][0] = > {"16,11,7,6"};
arrayValues[1]开发者_JAVA技巧[0] = > {"10,7,6,6"};

Any help would be appreciated. Thanks.


for(int i=0;i<2;i++) 
{
   for(int j=0;j<4;j++)
   {
     array[i][j]=e.getValues (r,c);


     arrayValues[i][0] += array[i][j];

     if(j < 3) {
       arrayValues[i][0] += ',';
     }

   }  
}


String[] s = new String[2];


String str = new String();
for(int i=0;i<2;i++) 
{
    str = "";
    for(int j=0;j<4;j++)
    {
       array[i][j]=e.getValues (r,c);

       str += Integer.toString(array[i][j]);
       if(j != 3) str += ",";

    }

    s[i] = str;
}


String [] newValues = new String[array.length];

for(int i=0;i<newValues.length;i++) {
 for(int j=0;j<array[i].length;j++) {
     newValues[i]= java.util.Arrays.toString(array[i]);
 }
}

You can test this by running:

for(int i=0;i<newValues.length;i++) {
    System.out.println(newValues[i]);
}

Which will print out:

[16, 11, 7, 6]
[10, 7, 6, 6]

If the exact string format you described is necessary, you can change the function to:

for(int i=0;i<newValues.length;i++) {
 for(int j=0;j<array[i].length;j++) {
     newValues[i]= java.util.Arrays.toString(array[i])
               .replace(" ", "").replace("[","{").replace("]","}");
 }
}

Which will print out:

{16,11,7,6}
{10,7,6,6}


If your question is how to take array and convert it to one string that contains coma delimited values, do the following:

String[] arr = new String[] {1, 2, 3, 4}
String str = Arrays.asList(arr).toString(); // contians "[1, 2, 3, 4]"
String result = str.substring(1, str.length - 1); // contains "1, 2, 3, 4"

if you want to remove spaces after comas call replace(", ", "")

And please note that 2 dimensional array is an array of arrays, so you can easily apply this way to your 2 dimensional array be calling this code in loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消