获得前25个字符的微小方法

Duk*_*ets 10 c# string

任何人都可以想到一个更好的方法来做到以下几点:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description : this.Description.Substring(0, 25) + "..."; }
}
Run Code Online (Sandbox Code Playgroud)

我本来希望只做string.Substring(0,25),但如果字符串小于提供的长度,它会引发异常.

Mic*_*tum 28

我经常需要这个,我为它写了一个扩展方法:

public static class StringExtensions
{
    public static string SafeSubstring(this string input, int startIndex, int length, string suffix)
    {
        // Todo: Check that startIndex + length does not cause an arithmetic overflow - not that this is likely, but still...
        if (input.Length >= (startIndex + length))
        {
            if (suffix == null) suffix = string.Empty;
            return input.Substring(startIndex, length) + suffix;
        }
        else
        {
            if (input.Length > startIndex)
            {
                return input.Substring(startIndex);
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你只需要它一次,那就是矫枉过正,但如果你经常需要它,它就会派上用场.

编辑:添加了对字符串后缀的支持.传入"...",你可以在较短的字符串上得到你的省略号,或者传入string.Empty,没有特殊的后缀.


Wel*_*bog 23

return this.Description.Substring(0, Math.Min(this.Description.Length, 25));
Run Code Online (Sandbox Code Playgroud)

没有这个...部分.实际上,你的方式可能是最好的.


mar*_*mka 11

public static Take(this string s, int i)
{
    if(s.Length <= i)
        return s
    else
        return s.Substring(0, i) + "..."
}

public string ShortDescription
{
    get { return this.Description.Take(25); }
}
Run Code Online (Sandbox Code Playgroud)


tdd*_*key 6

你做的方式对我来说似乎很好,除了我会使用幻数25,我将它作为一个常量.

你真的想把它存放在你的豆子里吗?大概这是为了显示某处,所以你的渲染器应该是截断而不是数据对象的东西