using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eugen.ESystem.Windows.Forms
{
public static class FixLineLenght
{
///
/// Formats a string with a fixed line length.
///
static FixLineLenght()
{
}
///
/// Formats a string with a fixed line length.
///
/// String to be formatted.
/// Maximum line length
///
public static string Format(string text, int lineLenght)
{
int ratedLenght = 0;
int spacePos = 0;
int currentPos = 0;
string character = "";
string resultText = "";
if (text.Length <= lineLenght)
{
resultText = text;
}
else
{
while (text.Length > 0)
{
while (ratedLenght < lineLenght)
{
if (currentPos < text.Length)
{
character = text.Substring(currentPos, 1);
}
else
{
break;
}
if (character == "\n" || character == "\r")
{
currentPos++;
ratedLenght = 0;
}
if (character == " " || character == "\\")
{
spacePos = currentPos;
}
currentPos++;
ratedLenght++;
}
if (spacePos == 0)
{
spacePos = currentPos;
}
if (text.Length <= lineLenght || text.Length == spacePos)
{
resultText = resultText + text;
text = "";
}
else
{
resultText = resultText + text.Remove(spacePos) + Environment.NewLine;
text = text.Remove(0, spacePos);
if (text.StartsWith(" "))
{
text = text.Remove(0, 1);
}
}
ratedLenght = 0;
currentPos = 0;
spacePos = 0;
}
}
resultText = CorrectLastLine(resultText, lineLenght);
return resultText;
}
private static string CorrectLastLine(string text, int lineLenght)
{
string tempMid = "";
string tempEnd = "";
tempEnd = text.Remove(0, text.LastIndexOf(Environment.NewLine) + 2);
tempMid = text.Remove(text.LastIndexOf(Environment.NewLine));
tempMid = tempMid.Remove(0, tempMid.LastIndexOf(Environment.NewLine) + 2);
if ((tempMid.Length + tempEnd.Length) <= lineLenght)
{
return text.Remove(text.LastIndexOf(Environment.NewLine), 2);
}
else
{
return text;
}
}
}
}