【发布时间】: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 <= arraySize)是您的错误的来源 - 我猜应该是while (j < arraySize)。 -
^^ 和
int j = 1;立即响起所有警报。顺便说一句:new char[arraySize - 1];创建一个长度为 4 的数组,索引从 0 到 3。
标签: c# arrays loops multidimensional-array jagged-arrays