Thomas Bandt

Über mich | Kontakt | Archiv

C# - Zeilen einrücken

Nachfolgend eine schnell getippte Methode, die sich einen Text nimmt und diesen einrückt - wie man es etwa aus Mailclients gewohnt ist. Perfekt bis ins letzte Detail ist es noch nicht, aber ich habe mit Outlook verglichen - da kann sie sich dem Wettbewerb getrost stellen, denn Outlook versagt ab einem gewissen Level ebenfalls ;-).

public static string IndentText(string text, string prefix, int lineLength)
{

    if (string.IsNullOrEmpty(text))
        return text;

    StringBuilder result = new StringBuilder(string.Empty);
    string[] paragraphs = text.Split(Environment.NewLine.ToCharArray());

    for (int y = 0; y <= paragraphs.Length - 1; y++)
    {
        string p = paragraphs[y];
        if (p.Trim().Length > 0)
        {
            for (int i = 0; i <= p.Length; i = i + lineLength)
            {
                string line;
                if (p.Length >= i + lineLength)
                {
                    line = p.Substring(i, lineLength);
                    int lastSpace = line.LastIndexOf(" ");
                    if (lastSpace > -1 && lastSpace < lineLength)
                        line = line.Substring(0, lastSpace);
                    i = i - lineLength + lastSpace;
                }
                else
                {
                    line = p.Substring(i, p.Length - i);
                }
                result.Append(Environment.NewLine + prefix + line.TrimStart());
            }
            if (y + 1 <= paragraphs.Length - 1)
                result.Append(Environment.NewLine + prefix);
        }
    }

    text = result.ToString();
    text = text.Replace(Environment.NewLine + prefix + Environment.NewLine + prefix + prefix, Environment.NewLine + prefix + prefix);

    return text;

}



« Zurück  |  Weiter »