Problem with Substring() - ArgumentOutOfRangeException

后端 未结 11 1659
抹茶落季
抹茶落季 2020-12-20 11:29

I have a repeater that displays data from my Projects table. There are projectId, name and description. I use Substring(1, 240) on description. But sometimes the string is s

相关标签:
11条回答
  • 2020-12-20 12:19
    string dec = "description";
    string result = dec.Substring( 0, dec.Length > 240 ? 240 : dec.Length )
    
    0 讨论(0)
  • 2020-12-20 12:19

    An extension method:

    public static string SafeSubstring(this string text, int start, int length)
    {
       if (start >= text.Length)
          return "";            
       if (start + length > text.Length)
          length = text.Length - start;         
       return text.Substring(start, length);
    }
    
    0 讨论(0)
  • 2020-12-20 12:22

    Let's try to keep this simple...

    We only need to truncate to a given max length, so how about we call it what it is:

    description.TruncateTo(240);
    

    The extension method that enables the above (ellipsis is appended by default if truncated):

    public static class StringExtensions
    {
        public static string TruncateTo(this string val, int maxLength, bool ellipsis = true)
        {
            if (val == null || val.Length <= maxLength)
            {
                return val;
            }
    
            ellipsis = ellipsis && maxLength >= 3;
            return ellipsis ? val.Substring(0, maxLength - 3) + "..." : val.Substring(0, maxLength);
        }
    }
    
    0 讨论(0)
  • 2020-12-20 12:25

    Based on Jon Skeet's answer, I think it should be checking for null or else it's not exactly a safe method :)

    public static string SafeSubstring(this string text, int start, int length)
    {
        if (text == null) return null;      
    
        return text.Length <= start ? ""
            : text.Length - start <= length ? text.Substring(start)
            : text.Substring(start, length);
    }
    
    0 讨论(0)
  • 2020-12-20 12:32
    Text='<%# Eval("Description").ToString().Substring(1, Math.Min(240, Eval("Description").ToString().Length - 1)) + "..." %>'
    
    0 讨论(0)
提交回复
热议问题