CSharp · Console
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Console1;
public static class Program
{
public static void Main()
{
string text = "DELICIOUS FOOD";
int cols = 5;
int rows = (text.Length + cols - 1) / cols;
var array = new char[rows, cols];
var span = AsSpan<char>(array); // Create a span that encompasses all the elements of 'array' as a single span.
text.CopyTo(span); // Copy the text to the span; this will wrap at the correct places.
span.Slice(text.Length).Fill('X'); // Fill the remainder of the span with 'X'.
// Print the result.
for (int r = 0; r < rows; ++r)
{
for (int c = 0; c < cols; ++c)
{
Console.Write(array[r, c]);
}
Console.WriteLine();
}
}
public static Span<T> AsSpan<T>(Array array)
{
return MemoryMarshal.CreateSpan(
ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(array)),
array.Length);
}
}