Cấp bậc tác giả:

DOTNET

Cắt Chuỗi Thành Nhiều Dòng Với Số Ký Tự Quy Định

Được viết bởi webmaster ngày 13/12/2015 lúc 12:29 AM
Cắt chuỗi thành nhiều dòng với số ký tự quy định và không cắt đôi một từ có nghĩa. Code sưu tầm và đã kiểm chứng tính đúng đắn.
  • 0
  • 5792

Cắt Chuỗi Thành Nhiều Dòng Với Số Ký Tự Quy Định

/// <summary>
    /// Strings the cut out.
    /// </summary>
    /// <param name="strInput">The string input.</param>
    /// <param name="charsPerLine">The chars per line.</param>
    /// <returns>The collection of all string per line</returns>
    public static IList<string> StringCutOutToList(string strInput, int charsPerLine = 120)
    {
        int pos, next;
        var lstResult = new List<string>();
 
        // Lucidity check
        if (charsPerLine < 1)
            return lstResult;
 
        // Parse each line of text
        for (pos = 0; pos < strInput.Length; pos = next)
        {
            // Find end of line
            int eol = strInput.IndexOf(Environment.NewLine, pos, StringComparison.Ordinal);
            if (eol == -1)
                next = eol = strInput.Length;
            else
                next = eol + Environment.NewLine.Length;
 
            // Copy this line of text, breaking into smaller lines as needed
            if (eol > pos)
            {
                do
                {
                    int len = eol - pos;
                    if (len > charsPerLine)
                        len = BreakLine(strInput, pos, charsPerLine);
                    lstResult.Add(strInput.Substring(pos, len));
 
                    // Trim whitespace following break
                    pos += len;
                    while (pos < eol && Char.IsWhiteSpace(strInput[pos]))
                        pos++;
                } while (eol > pos);
            }
        }
 
        return lstResult;
    }
 
    /// <summary>
    /// Locates position to break the given line so as to avoid
    /// breaking words.
    /// </summary>
    /// <param name="text">String that contains line of text</param>
    /// <param name="pos">Index where line of text starts</param>
    /// <param name="max">Maximum line length</param>
    /// <returns>The modified line length</returns>
    private static int BreakLine(string text, int pos, int max)
    {
        // Find last whitespace in line
        int i = max;
        while (i >= 0 && !Char.IsWhiteSpace(text[pos + i]))
            i--;
 
        // If no whitespace found, break at maximum length
        if (i < 0)
            return max;
 
        // Find start of whitespace
        while (i >= 0 && Char.IsWhiteSpace(text[pos + i]))
            i--;
 
        // Return length of text before whitespace
        return i + 1;
    }

Nguồn bài viết: Sưu tầm

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML