Truncate string on whole words in .NET C#

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

    Try the following. It is pretty rudimentary. Just finds the first space starting at the desired length.

    public static string TruncateAtWord(this string value, int length) {
        if (value == null || value.Length < length || value.IndexOf(" ", length) == -1)
            return value;
    
        return value.Substring(0, value.IndexOf(" ", length));
    }
    

提交回复
热议问题