Cut the string to be <= 80 characters AND must keep the words without cutting them

前端 未结 4 1631
春和景丽
春和景丽 2021-01-24 07:22

I am new to C#, but I have a requirement to cut the strings to be <= 80 characters AND they must keep the words integrity (without cutting them)

Examples

4条回答
  •  没有蜡笔的小新
    2021-01-24 07:32

    string truncatedText = text.Substring(0, 80);  // truncate to 80 characters
    if (text[80] != ' ')  // don't remove last word if a space occurs after it in the original string (in other words, last word is already complete)
        truncatedText = truncatedText.Substring(0, truncatedText.LastIndexOf(' '));  // remove any cut-off words
    

    Updated to fix issue from comments where last word could get cut off even if it is complete.

提交回复
热议问题