如果不使用 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();
}
}
uj5u.com熱心網友回復:
沒有 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("}");
}
}
uj5u.com熱心網友回復:
.Net 6,目前可作為候選發布版本,但預計現在任何一天都會有 GA 版本,它將具有IEnumerable<T>.Chunk():
var result = stringContent.Chunk(5);
foreach(char[] segment in result)
{
foreach(char c in segment)
{
Console.Write(c);
}
Console.WriteLine();
}
現在我知道未發布的方法可能對您沒有幫助,尤其是當您要求沒有 linq 時。但是,如果您自己實作該方法,則它并不是真正的 linq:
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;頂部的缺失。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341249.html
下一篇:Axios不POSTing陣列
