【问题标题】:From string to jagged array of chars从字符串到锯齿状的字符数组
【发布时间】:2021-12-14 13:44:55
【问题描述】:

如果不使用 LINQ,我该如何解决这个问题?

我有一个字符串:string stringContent = "Loremipsumdolorsitamet";

以及行的大小(最大列):int arraySize = 5;

然后我必须得到这个结果:

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

到目前为止我的代码:

  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();
            }
        }

【问题讨论】:

  • 你的代码有什么问题?
  • @SomeBody System.IndexOutOfRangeException: '索引超出了数组的范围。'
  • 而且我不知道这里到底出了什么问题。尝试一切新事物。
  • IndexOutOfRangeException 意味着您尝试访问数组的索引 =您的数组长度。如果不详细阅读您的代码,很可能while (j &lt;= arraySize) 是您的错误的来源 - 我猜应该是while (j &lt; arraySize)
  • ^^ 和int j = 1; 立即响起所有警报。顺便说一句:new char[arraySize - 1]; 创建一个长度为 4 的数组,索引从 0 到 3。

标签: c# arrays loops multidimensional-array jagged-arrays


【解决方案1】:

没有 LINQ,根据要求,使用 .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("}");
        }
    }

【讨论】:

    【解决方案2】:

    .Net 6,目前作为候选版本提供,但预计现在任何一天都会发布,它将拥有IEnumerable&lt;T&gt;.Chunk()

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

    现在我知道未发布的方法可能对您没有帮助,尤其是当您要求不使用 linq 时。但是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;
        }
    }
    

    在这里看到它的工作......

    https://dotnetfiddle.net/r5YAZV

    ...并注意顶部缺少​​using System.Linq;

    【讨论】:

    • 应该是foreach(char[] segment in result)也应该是Console.WriteLine(segment);会比第二个foreach简单
    • @Charlieface 对 char[] 正确,已修复。我知道有更好的方法来编写输出,但我希望更接近 OP 在问题中所做的事情。
    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多