1

I have an array of strings which I create using:

String[] tmp = new String[10];
        int i = 0;
        while (input.hasNextLine()){
            tmp[i++]=input.nextLine();
        }

This creates the following array:

[eoksibaebl, ropeneapop, mbrflaoyrm, gciarrauna, utmorapply, wnarmupnke, ngrelclene, alytueyuei, fgrammarib, tdcebykxka]

Now lets say I want to access the third letter (k) of the first string (eoksibaebl) and assign it to another variable, how would I do that?

What my end aim is to do is to take all the letters and assign them to a 2d character array (char[N][N]).

If anyone can help me do that I'd appreciate it.

Sergei Danielian
  • 4,938
  • 4
  • 36
  • 58
Javanewbie
  • 39
  • 8

1 Answers1

0

You can use String.charAt(int index) method.

See Get string character by index - Java for more info about getting the i-th character from a string.

To set the values from the strings to the 2 dimensional array you will have to iterate over the each of the strings array and then iterate over it's characters.

something like:

String[] strings = {"abc", "test", "123"};
char[][] charArray = new char[strings.length][];
for(int i=0; i < strings.length; i++) {
   for(int j=0; j < strings[i].length(); j++) {
      charArray[i] = new char[strings[i].length()];
      charArray[i][j] = strings[i].charAt(j);
   }
}

you can also use String.toCharArray() to skip the second nested for loop.

String[] strings = {"abc", "test", "123"};
char[][] charArraay = new char[strings.length][];
for(int i=0; i < strings.length; i++) {
   charArraay [i] = strings[i].toCharArray();
}

Then charArraay will contain your data.

kamentk
  • 513
  • 3
  • 12