[英]Converting a 2d array of ints to char and string in Java
How can I convert the ints in a 2d array into chars, and strings? 如何将2d数组中的int转换为char和字符串? (seperately)
(seperately)
If I copy ints to a char array i just get the ASCII code. 如果我将整数复制到char数组中,我只会得到ASCII码。
For example: 例如:
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Thanks 谢谢
This question is not very well-phrased at all. 这个问题的措辞根本不够好。 I THINK what you're asking is how to convert a two-level array of type
int[][]
to one of type String[][]
. 我想您要问的是如何将
int[][]
类型的两级数组转换为String[][]
类型的String[][]
。
Quite frankly, the easiest approach would simply leave your array as-is... and convert int
values to String
's when you use them: 坦白说,最简单的方法就是将数组保持原状...并在使用它们时将
int
值转换为String
:
Integer.toString(a[5][5]);
Alternatively, you could start with a String[][]
array in the first place, and simply convert your int
values to String
when adding them: 另外,您可以首先从
String[][]
数组开始,并在添加它们时将int
值简单地转换为String
:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][]
to one of type String[][]
, you would have to do so manually with a two-layer for()
loop: 如果确实需要将
int[][]
类型的数组转换为String[][]
类型的String[][]
,则必须使用两层for()
循环手动进行此操作:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
All three of these approaches would work equally well for conversion to type char
rather than String
. 这三种方法对于转换为
char
类型而不是String
都将同样有效。
Your code must basically go through your array and transform each int value into a String. 您的代码基本上必须遍历数组并将每个int值转换为String。 You can do this with the
String.toString(int)
method. 您可以使用
String.toString(int)
方法执行此操作。
You can try that : 您可以尝试:
String[][] stringArray = new String[a.length][];
for(int i = 0; i < a.length; i++){
stringArray[i] = new String[a[i].lenght];
for(int j = 0; j < a[i].length; j++){
stringArray[i][j] = Integer.toString(a[i][j]);
}
}
如果要将int数字作为字符串,则可以使用Integer.toString()
函数。
b[1][1] = Integer.toString(a[1][1]);
String [][]b = new String[a.length][];
for(int i=0; i<a.length; i++) {
int [] row = a[i];
b[i] = new String[row.length];
for(int j=0; j<row.length; j++) {
b[i][j] = Integer.toString(row[j]);
}
}
要将2D数组转换为String,可以使用Arrays.deepToString(stringArr)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.