2

I got a little problem here with Java and I am fairly new to it.

My program reads a String via InputStreamReader and saves it in the String input.

How do I save the elements of the String in a 2d char array with n x m elements?

Edit: I think I´ve got a solution:

I used 2 for-loops (is that the right english translation for it? ) and .toCharArray to convert the String.

public static char[][] transform (String text, int arrBreite, int arrLaenge) {
    char[][] returnArray = new char[arrBreite][arrLaenge];

    char[] buffer = text.toCharArray();
    for (int i = 0; i < arrBreite; i++) {
        for (int j = 0; j <arrLaenge; j++) {
            if (((i * arrBreite) + j) > buffer.length - 1) returnArray[i][j] = " ".charAt(0);
            else returnArray[i][j] = buffer[(i*arrBreite)+j];
        }
    }

    return returnArray;
}

Thanks for your help guys.

5
  • 7
    Have you read the JavaDoc for String? Commented Dec 15, 2011 at 13:35
  • For what reason do you need a 2d array of chars? Commented Dec 15, 2011 at 13:36
  • Please provide an example how you want chars to be placed inside your char[][]?! Giving input and a matrix how it should look like after work is done. Commented Dec 15, 2011 at 13:37
  • There's no natural mapping from a String to a 2d character array. What exactly are the requirements here? How do you know what the dimensions of your 2d array are? Commented Dec 15, 2011 at 13:37
  • I´ve to do a Scytale De-/Encrypter and we should use an 2D Array for it. Commented Dec 15, 2011 at 13:45

2 Answers 2

1

You can use the toCharArray() method to get a char array from your String.

If you need to split with a given delimiter to determine the array lines, you use first the Split method on the String, then use toCharArray to create your 2 dimensional array.

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

Comments

0

You should use String.toCharArray().

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.