Reputation: 35
I have this code and I want to put the string I have in a char array in java, but the problem I have is whenever I use toCharArray() the array reduces its index so, what can I do to keep the array by the same original index?
public static void main(String[] args) {
String str = "cat";
char[][] carray;
carray = new char[5][5];
char[] chararray = new char[5];
chararray = str.toCharArray();
for(int i=0;i<5;i++){
carray[i][0] = chararray[i];
}
System.out.println(carray);
for(int i=0;i<5;i++){
System.out.println("65"+carray[i][0]);
}
Upvotes: 1
Views: 368
Reputation: 201537
There are only three characters in "cat" (not five). Instead of hardcoding the length, use the String
to determine the correct length. Also, your second array dimension should only be one (since you are only copying a single character at a time). Like,
String str = "cat";
char[] chararray = str.toCharArray();
char[][] carray = new char[chararray.length][1];
for (int i = 0; i < carray.length; i++) {
carray[i][0] = chararray[i];
}
System.out.println(Arrays.deepToString(carray));
for (int i = 0; i < carray.length; i++) {
System.out.println("65" + carray[i][0]);
}
Upvotes: 0