2

I wanted to convert the String array elements into char array

For Example:

String str[]={"abc","defl","ghi"};

I wanted to store the characters in str array to be stored in char arr[] in different indexes

For Ex:
char ch[0][]={'a','b','c'};
     ch[1][]={'d','e','f','l'};
     ch[2][]={'g','h','i'};

I wanted to do this dynamically,I am able to split the string to characters ,but not able to store it in this order.

5 Answers 5

3

Use the following code:

char[][] array = new char[str.length][];
for(int i = 0; i< str.length; i++){
    array[i] = str[i].toCharArray();
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you are using Java 8, you can do

char[][] arr = Stream.of(str).map(String::toCharArray).toArray(char[][]::new);

Comments

0

Simply:

char[][] ch = new char[str.length];
for(int i = 0 ; i < str.length ; ++i) {
    ch[i] = str[i].toCharArray();
}

1 Comment

You won by 36 seconds. :P
0

You can initialize a 2D char array without specifying the length of each of array in the 2D array. By doing this, you'll have a 2D array of null arrays because each array will be of different length, depending on the number of characters in the string. So depending on corresponding element in str, the arrays of the char 2D array will have lengths equal to the length of string in str after initializing the arrays. Each string in your string array str will represent an array in the 2D char array. Each array in the 2D array will contain the characters of the string. This is how you would achieve this.

char[][] charArr = new char[str.length]; //number of arrays in 2d array 
                                         //is length of str array
for(int i = 0; i < charArr.length; i++){ //initializing the arrays in charArr
    charArr[i] = new char[str[i].length()];
}
for(int i = 0; i < charArr.length; i++){ //to store the chars in the 2d array
    for(int j = 0; j < charArr[i].length; j++){
          char[i][j] = str[i].charAt(j);
    }
}

Comments

0

Assuming that you are using Java 8:

char[][] chars = Stream.of(str).sequential().map(String::toCharArray).toArray(char[][]::new);

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.