Chops a line at a word boundary at or before , adding ellipsis at the end if it was chopped. - CSharp System

CSharp examples for System:String Strip

Description

Chops a line at a word boundary at or before , adding ellipsis at the end if it was chopped.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;/*from w  ww  .  j a v  a 2s  . c  o m*/

public class Main{
        /// <summary>
        /// Chops a line at a word boundary at or before <paramref name="maxlength"/>, adding ellipsis at the end
        /// if it was chopped.
        /// </summary>
        /// <param name="line">Input text to chop.</param>
        /// <param name="maxlength">Maximum length of the output string. Final result may be fewer characters than this.</param>
        /// <param name="ellipsis">The string to use for ellipsis characters, e.g. "..."</param>
        /// <param name="wordbreaks">Set of characters used to END words. For pairing characters (e.g. brackets) only include the ending pair character.</param>
        /// <returns></returns>
        public static string ChopToWordWithEllipsis(this string line, int maxlength, string ellipsis, params char[] wordbreaks)
        {
            if (string.IsNullOrEmpty(line)) return line;

            if ((wordbreaks == null) || (wordbreaks.Length == 0)) wordbreaks = WordBreakChars;

            if (line.Length > maxlength)
            {
                var idx = line.LastIndexOfAny(wordbreaks, maxlength - 1);
                if (idx < 0) idx = maxlength; else ++idx;
                return line.Substring(0, idx) + ellipsis;
            }
            return line;
        }
        /// <summary>
        /// Checks if the string is null or empty or just a bunch of worthless whitespace.
        /// </summary>
        /// <remarks>This works because extension methods can be called on null references.</remarks>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string self)
        {
            if (self == null) return true;
            if (self.Length == 0) return true;
            // NOTE: This is the kicker over String.IsNullOrEmpty()
            return self.Trim().Length == 0;
        }
}

Related Tutorials