Problem
A single line should be separated by Environment.NewLine
so that each row has a length of columns
(expect offor the last one that may mebe shorter).
Below is my solution:
public static string Wrap(this string singleLineString, int columns)
{
if (singleLineString == null)
throw new ArgumentNullException("singleLineString");
if (columns < 1)
throw new ArgumentException("'columns' must be greater than 0.");
var rows = Math.Ceiling((double)singleLineString.Length/columns);
if (rows < 2) return singleLineString;
var sb = new StringBuilder();
for (int i = 0; i < rows; i++)
{
if (i > 0) sb.Append(Environment.NewLine);
var index = i*columns;
var length = Math.Min(columns, singleLineString.Length - index);
var line = singleLineString.Substring(index, length);
sb.Append(line);
}
return sb.ToString();
}
Even if the problem is really simple, there are lots of thinkable approaches to solve it. Is there simpler / more elegant solution than the one aboveeabove?