Home > Software engineering >  From string to jagged array of chars
From string to jagged array of chars

Time:10-30

Without using LINQ, how can I approach this issue?

I have a string: string stringContent = "Loremipsumdolorsitamet";

and the size of rows (max columns): int arraySize = 5;

and then I have to get this result:

{
    { 'L', 'o', 'r', 'e', 'm' },
    { 'i', 'p', 's', 'u', 'm' },
    { 'd', 'o', 'l', 'o', 'r' },
    { 's', 'i', 't', 'a', 'm' },
    { 'e', 't' }
}

My code so far:

  static void Main(string[] args)
        {
            int arraySize = 5;
            string stringContent = "Loremipsumdolorsitamet";
            int length = stringContent.Length / arraySize;
            char[][] save = new char[length   1][]; // Length   1 is for the extra lien at the end F.E 'e' 't'

            
            int charIndex = 0; // this is fo
            for (int i = 0; i < length; i  )
            {
                char[] line = new char[arraySize - 1];
                int j = 1;
                while (j <= arraySize)
                {
                    if (charIndex < stringContent.Length)
                    {
                        line[j] = stringContent[charIndex]; 
                        charIndex  ;
                    }

                    j  ;
                }

                save[i] = line;
            }

            for (int i = 0; i < length; i  )
            {
                for (int k = 0; k < arraySize; k  )
                {
                    Console.Write(save[i][k]);
                }

                Console.WriteLine();
            }
        }

CodePudding user response:

Without LINQ, as requested, simpler version using the .Net API:

    class Program
    {
        static void Main(string[] args)
        {
            char[][] result = ToArrays("Loremipsumdolorsitamet", 5);
            WriteResult(result, Console.Out);
        }

        private static char[][] ToArrays(string text, int arraySize)
        {
            var arrs = new List<char[]>();

            while (!string.IsNullOrEmpty(text))
            {
                int len = Math.Min(arraySize, text.Length);
                string chunk = text.Substring(0, len);
                text = text.Substring(len);
                arrs.Add(chunk.ToCharArray());
            }

            return arrs.ToArray();
        }

        private static void WriteResult(char[][] result, TextWriter writer)
        {
            writer.WriteLine("{");
            foreach (char[] arr in result)
            {
                writer.Write("\t{ '");
                writer.Write(string.Join("', '", arr));
                writer.WriteLine("' }");
            }
            writer.WriteLine("}");
        }
    }

CodePudding user response:

.Net 6, currently available as a release candidate but with GA expected any day now, will have IEnumerable<T>.Chunk():

var result = stringContent.Chunk(5);
foreach(char[] segment in result)
{
    foreach(char c in segment)
    {
        Console.Write(c);
    }
    Console.WriteLine();
}

Now I know an unreleased method probably doesn't help you, especially as you asked for no linq. But it's not really linq if you implement the method yourself:

public static IEnumerable<T[]> Chunk<T>(this IEnumerable<T> values, int chunkSize)
{
    T[] items = new T[chunkSize];
    int i = 0;
    var e = values.GetEnumerator();
    while (e.MoveNext())
    {
        items[i] = e.Current;
        i  ;

        if (i == chunkSize) {
            yield return items;
            items = new T[chunkSize];
            i = 0;
       }
    }
    if (i != 0) //partial array remaining
    { 
       T[] final = new T[i];
       while (i>0) final[--i] = items[i];
       yield return final;
    }
}

See it work here...

https://dotnetfiddle.net/r5YAZV

... and note the lack of using System.Linq; at the top.

  • Related