截断字符串在整个词语的.NET C#字符串、词语、在整个、NET

2023-09-02 11:50:17 作者:白鸥掠海

我想截断在C#中一些长期的文字,但我不希望我的字符串被截断一部分的方式,通过一个字。有没有人有,我可以用它来截断我字符串中的单词的末尾功能?

例如:

 这是一个很长的字符串...
 

 这是一个漫长的圣......
 

解决方案

谢谢您的回答大卫。我已经调整了功能一点,这是我使用的是什么......除非有任何更多的评论;)

 公共静态字符串TruncateAtWord(此字符串输入,INT的长度)
{
    如果(输入== NULL || input.Length<长度)
        返回输入;
    INT iNextSpace = input.LastIndexOf(,长度);
    返回的String.Format({0} ...,input.Substring(0,(iNextSpace大于0)iNextSpace:长度).Trim());
}
 
数组和字符串方法汇总及互为转换 共用方法汇总

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 string at the end of a word?

E.g:

"This was a long string..."

Not:

"This was a long st..."

解决方案

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);
    return string.Format("{0}...", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
}