怎么进行二维数组和String的互相转换
2个回答
2016-11-14 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
package test;
public class ArrayToStringTest {
public static void main(String[] args) {
int[][] array = new int[4][4];
int count = 0;
ArrayToStringTest test = new ArrayToStringTest();
// 赋值一个int[][]
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = count;
++count;
}
}
// 获取row,col
int row = test.getRow(array);
int col = test.getCol(array);
// 转为String
String str = test.convertToString(array, row, col);
System.out.println(str); // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
//转为int[][]
int[][] arrayConvert = new int[row][col];
arrayConvert = test.convertToArray(str, row, col);
}
public int getRow(int[][] array) {
int row = 0;
if (array != null) {
row = array.length; // 行
}
return row;
}
public int getCol(int[][] array) {
int col = 0;
if (array != null) {
col = array[0].length; // 列
}
return col;
}
public String convertToString(int[][] array, int row, int col) {
String str = "";
String tempStr = null;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
tempStr = String.valueOf(array[i][j]);
str = str + tempStr + ",";
}
}
return str;
}
public int[][] convertToArray(String str, int row, int col){
int[][] arrayConvert = new int[row][col];
int count = 0;
String[] strArray = str.split(",");
for(int i = 0 ; i < row ; i ++){
for(int j = 0 ; j < col ; j ++){
arrayConvert[i][j] = Integer.parseInt(strArray[count]);
++ count ;
}
}
return arrayConvert;
}
}
public class ArrayToStringTest {
public static void main(String[] args) {
int[][] array = new int[4][4];
int count = 0;
ArrayToStringTest test = new ArrayToStringTest();
// 赋值一个int[][]
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = count;
++count;
}
}
// 获取row,col
int row = test.getRow(array);
int col = test.getCol(array);
// 转为String
String str = test.convertToString(array, row, col);
System.out.println(str); // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
//转为int[][]
int[][] arrayConvert = new int[row][col];
arrayConvert = test.convertToArray(str, row, col);
}
public int getRow(int[][] array) {
int row = 0;
if (array != null) {
row = array.length; // 行
}
return row;
}
public int getCol(int[][] array) {
int col = 0;
if (array != null) {
col = array[0].length; // 列
}
return col;
}
public String convertToString(int[][] array, int row, int col) {
String str = "";
String tempStr = null;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
tempStr = String.valueOf(array[i][j]);
str = str + tempStr + ",";
}
}
return str;
}
public int[][] convertToArray(String str, int row, int col){
int[][] arrayConvert = new int[row][col];
int count = 0;
String[] strArray = str.split(",");
for(int i = 0 ; i < row ; i ++){
for(int j = 0 ; j < col ; j ++){
arrayConvert[i][j] = Integer.parseInt(strArray[count]);
++ count ;
}
}
return arrayConvert;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询