fayez jabra
fayez jabra

Reputation: 35

string to a char array in java

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

Answers (2)

Elliott Frisch
Elliott Frisch

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

Sanjeev Chauhan
Sanjeev Chauhan

Reputation: 46

Use str.charAt(i) instead of chararray[i]

That may be help.

Upvotes: 1

Related Questions