1

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]);
    }
4
  • 2
    What output are you getting? What do you expect? Commented Apr 15, 2018 at 1:52
  • if i keep the for loop for(int i=0;i<5;i++){ carray[i][0] = chararray[i]; } to i<5 it gives me an error that it exceeds index but if i make it i<3 it works fine Commented Apr 15, 2018 at 1:54
  • Please edit the question to add more information.... It's not really clear what you're trying to do. toCharArray doesn't alter index positions. And cat is only 3 letters, not 5. Plus, you do not need a char[][] to convert a string to a char array Commented Apr 15, 2018 at 1:55
  • this is an example or a small try out for a bigger project so i have a two dimensional array of char[][] but i also need to fill it from a string that a user inserts Commented Apr 15, 2018 at 1:58

2 Answers 2

1

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

That may be help.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you that helped a lot instead of creating an array i can use this method and it solves my problem
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.