Truncate string on whole words in .NET C#

前端 未结 10 1374
走了就别回头了
走了就别回头了 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:16

    Thanks for your answer Dave. I've tweaked the function a bit and this is what I'm using ... unless there are any more comments ;)

    public static string TruncateAtWord(this string input, int length)
    {
        if (input == null || input.Length < length)
            return input;
        int iNextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
        return string.Format("{0}…", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
    }
    

提交回复
热议问题