Tiny way to get the first 25 characters

后端 未结 12 1564
感动是毒
感动是毒 2020-12-29 13:12

Can anyone think of a nicer way to do the following:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description :          


        
12条回答
  •  轮回少年
    2020-12-29 14:14

    I needed this so often, I wrote an extension method for it:

    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;
                }
            }
        }
    }
    

    if you only need it once, that is overkill, but if you need it more often then it can come in handy.

    Edit: Added support for a string suffix. Pass in "..." and you get your ellipses on shorter strings, or pass in string.Empty for no special suffixes.

提交回复
热议问题