-2

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.

String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();

My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array

msrd0
  • 7,816
  • 9
  • 47
  • 82

2 Answers2

1

If you want the array to fill the first row, just asign it to the first row:

words[0] = str.toCharArray();

Since this will create a new array in the array, you should change the instantiation of words to this:

char[][] words = new char[5][];
msrd0
  • 7,816
  • 9
  • 47
  • 82
-1

Java has a String class. Make use of it.

Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.

Now onto the problem at hand, how would this code look now?

List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");

for (String s : words) {
    System.out.println(s);
}

For your case if you are stuck with using arrays.

String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();

Use something along the line of

String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();

for (int i = 0; i < 5; i++) {
    System.out.println(words[i]);
}

However, why invent the wheel again? There are cases however, more can be read on the subject here.

Array versus List<T>: When to use which?

Community
  • 1
  • 1
Emz
  • 1,280
  • 1
  • 14
  • 29