Truncate string on whole words in .NET C#

前端 未结 10 1367
走了就别回头了
走了就别回头了 2020-11-29 22:43

I am trying to truncate some long text in C#, but I don\'t want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my st

10条回答
  •  孤城傲影
    2020-11-29 23:34

    My contribution:

    public static string TruncateAtWord(string text, int maxCharacters, string trailingStringIfTextCut = "…")
    {
        if (text == null || (text = text.Trim()).Length <= maxCharacters) 
          return text;
    
        int trailLength = trailingStringIfTextCut.StartsWith("&") ? 1 
                                                                  : trailingStringIfTextCut.Length; 
        maxCharacters = maxCharacters - trailLength >= 0 ? maxCharacters - trailLength 
                                                         : 0;
        int pos = text.LastIndexOf(" ", maxCharacters);
        if (pos >= 0)
            return text.Substring(0, pos) + trailingStringIfTextCut;
    
        return string.Empty;
    }
    

    This is what I use in my projects, with optional trailing. Text will never exceed the maxCharacters + trailing text length.

提交回复
热议问题