2011-01-25 3 views
2

Je tableau à deux dimensions avec des valeurs créées comme suit:java tableau 2dimensional à tableau de chaînes

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

qui retournera:

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 

comment puis-je stocker ces valeurs comme une seule chaîne dans une autre 2d string array:

arrayValues[0][0] = > {"16,11,7,6"}; 
arrayValues[1][0] = > {"10,7,6,6"}; 

Toute aide serait appréciée. Merci.

Répondre

0

Si votre question est de savoir comment prendre tableau et le convertir en une chaîne qui contient des valeurs délimitées de coma, procédez comme suit:

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" 

si vous voulez supprimer les espaces après comas appel replace(", ", "")

Et Veuillez noter que le tableau à deux dimensions est un tableau de tableaux, vous pouvez donc facilement l'appliquer à votre tableau à deux dimensions en appelant ce code en boucle.

0
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]); 
} 
} 

Vous pouvez tester en exécutant:

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

qui imprimera:

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

Si le format exact de chaîne que vous avez décrite est nécessaire, vous pouvez changer la fonction vers:

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("]","}"); 
} 
} 

qui imprimera:

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

vraiment génial ... merci pour tout le monde ..... – Maya

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; 
} 
2
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] += ','; 
    } 

    } 
} 
Questions connexes