Search code examples
c#.netvisual-studiostreamreader

How can I populate jagged array with chars in c#


I am struggling to populate jagged array with chars My goal is to read string. slice them into chars, then populate jagged array with those chars

            "Lorem",
            5,
            new char[][]
            {
                new char[] { 'L', 'o', 'r', 'e', 'm' },
            },

or

            "Loremipsumdolorsitamet",
            5,
            new char[][]
            {
                new char[] { 'L', 'o', 'r', 'e', 'm' },
                new char[] { 'i', 'p', 's', 'u', 'm' },
                new char[] { 'd', 'o', 'l', 'o', 'r' },
                new char[] { 's', 'i', 't', 'a', 'm' },
                new char[] { 'e', 't' },
            },

like the example. above ints under the string represent arraySize(i.e. number of columns) and streamReader(see code under) is the string itself. I am using System.IO and System.Text

        var read = streamReader.ReadToEnd().ToCharArray();
        if (read.Length == 0)
        {
            return Array.Empty<char[]>();
        }

        char[][] jagArray = new char[read.Length / 5][];

        for (int p = 0; p < read.Length; p++)
        {
            for (int i = 0; i < read.Length / arraySize; i++)
            {
                jagArray[i] = new char[arraySize];

                for (int j = 0; j < arraySize; j++)
                {
                    jagArray[i][j] = read[p];
                }
            }
        }

        return jagArray;

I tried this code, but obviously it doesnt work.


Solution

  • Use this method to split a single char[] array into array of arrays, each of which is no longer than cols characters length:

    public static char[][] ToJaggedArray(char[] chars, int cols)
    {
        int rows = (chars.Length + cols - 1) / cols;
        char[][] jagArray = new char[rows][];
        for (int i = 0; i < rows; i++)
        {
            jagArray[i] = new char[Math.Min(cols, chars.Length - cols * i)];
        }
    
        for (int i = 0; i < chars.Length; i++)
        {
            int row = i / cols;
            int col = i % cols;
            jagArray[row][col] = chars[i];
        }
    
        return jagArray;
    }