Ellipsis with C# (ending on a full word)

后端 未结 2 1407
北恋
北恋 2021-01-12 06:51

I\'m trying to implement ellipsis in Umbraco, the requirement being 15 characters of intro text but always ending on a full word.

I thought of using XSLT, but then r

2条回答
  •  星月不相逢
    2021-01-12 07:06

    if (text.Length <= length) return text;
    int pos = text.IndexOf(" ", length) ;
    if (pos >= 0)
        return text.Substring(0, pos) + "...";
    return text;
    

    Edit: This is the program I tested it with:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1 {
        class Program {
            static void Main(string[] args) {
                for (int i = 0; i < 40; ++i) {
                    string s = Ellipsis("Lorem ipsum dolor sit amet, amet consectetur adipiscing elit.", i);
                    Console.WriteLine("{0} : {1}", i, s);
                }
            }
    
            static public string Ellipsis(string text, int length) {
              if (text.Length <= length) return text;
              int pos = text.IndexOf(" ", length) ;
              if (pos >= 0)
                return text.Substring(0, pos) + "...";
              return text;
            }
        }
    }
    

    Here is output:

    0 : Lorem...
    1 : Lorem...
    2 : Lorem...
    3 : Lorem...
    4 : Lorem...
    5 : Lorem...
    6 : Lorem ipsum...
    7 : Lorem ipsum...
    8 : Lorem ipsum...
    9 : Lorem ipsum...
    10 : Lorem ipsum...
    11 : Lorem ipsum...
    12 : Lorem ipsum dolor...
    13 : Lorem ipsum dolor...
    14 : Lorem ipsum dolor...
    15 : Lorem ipsum dolor...
    16 : Lorem ipsum dolor...
    17 : Lorem ipsum dolor...
    18 : Lorem ipsum dolor sit...
    19 : Lorem ipsum dolor sit...
    20 : Lorem ipsum dolor sit...
    21 : Lorem ipsum dolor sit...
    22 : Lorem ipsum dolor sit amet,...
    23 : Lorem ipsum dolor sit amet,...
    24 : Lorem ipsum dolor sit amet,...
    25 : Lorem ipsum dolor sit amet,...
    26 : Lorem ipsum dolor sit amet,...
    27 : Lorem ipsum dolor sit amet,...
    28 : Lorem ipsum dolor sit amet, amet...
    29 : Lorem ipsum dolor sit amet, amet...
    30 : Lorem ipsum dolor sit amet, amet...
    31 : Lorem ipsum dolor sit amet, amet...
    32 : Lorem ipsum dolor sit amet, amet...
    33 : Lorem ipsum dolor sit amet, amet consectetur...
    34 : Lorem ipsum dolor sit amet, amet consectetur...
    35 : Lorem ipsum dolor sit amet, amet consectetur...
    36 : Lorem ipsum dolor sit amet, amet consectetur...
    37 : Lorem ipsum dolor sit amet, amet consectetur...
    38 : Lorem ipsum dolor sit amet, amet consectetur...
    39 : Lorem ipsum dolor sit amet, amet consectetur...
    

提交回复
热议问题