2

I need to convert a string array into a 2 dimensional char array

Example: My string array looks like

string[] months = {"January", "February", "March"....};

I want to convert it into a char[,] something like this (not sure about syntax)

char[][] = {
    {'J','a','n','u','a','r','y'},
    {'F','e','b','r','u','a','r','y'},
    {'M','a','r','c','h'}
};

what is the best way to achieve this?

5
  • 2
    A char[,] is a rectangular array, meaning each dimension has the same length. That is not the case in your example. You could convert it to a char[][] Commented Jul 4, 2016 at 10:59
  • what kind of 2D array does your DLL expect? [,] or [][] ? in the first case you probably would need to fill the missing items with empty strings Commented Jul 4, 2016 at 11:03
  • Yes.. my bad.. Dll expects 2D array of form [][].. I will edit the question.. Commented Jul 4, 2016 at 11:07
  • @ChaitanyaArawakar - Does my answer answer your question? or do you need help to turn it into a char[,]? Commented Jul 4, 2016 at 11:27
  • @GiladGreen you answer was very helpful.. it solved my issue.. thanks for your help.. Commented Jul 4, 2016 at 11:34

2 Answers 2

8

You can do this:

string[] months = { "January", "February", "March" };
char[][] result = months.Select(item => item.ToArray()).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

@Gilad green I need to pass 2d char array as a parameter to one of the functions from DLL, so this option will not work for me.. but thanks for your effort to help..
@ChaitanyaArawakar this will gives you 2d array of char, what you looking for. Use char[][] result = instead of var
0

Try like this,

string[] months = {"January", "February", "March"};

char[][] jaggedOfChar =new char[3][];

for (int i = 0; i < months.Length; i++)
{
    char[] s = months[i].ToCharArray();
    jaggedOfChar[i] = s;
}

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.