简体   繁体   中英

Limit Character count in c# String

I have this code, is there an easy way to limit the amount of characters displayed to 250?

<%# trimIt(DataBinder.Eval(Container.DataItem, "WebSalesText").ToString())%>

public string trimIt(string s)
{
    if (s.Length > 0 && s.IndexOf(".") > 0)
    {
        return (s.Substring(0, s.IndexOf(".")) + " ...");
    }
    else
    {
        return s;
    }
}

Are you looking for an implementation of trimIt?

public static string trimIt(string s)
{
   if(s == null)
       return string.Empty;

   int count = Math.Min(s.Length, 250);
   return s.Substring(0, count);
}

You could make an extension method for string to doing what you need and allow you to specify the amount to allow to be the maximum length.

public static string TrimToMaxSize(this string input, int max)
{
   return ((input != null) && (input.Length > max)) ?
       input.Substring(0, max) : input;
}

We can use below methods,

  public static string RTrim(this string s, int Length) { if (s == null) return string.Empty; return s.Substring(0, s.Length - Length); } 

AND

  public static string LTrim(this string s, int Length) { if (s == null) return string.Empty; if (s.Length >= Length) { return s.Substring(0, Length); } else { return s; } } 

This does not work, as SubString will fail for a string shorter than 250 signs.:

<%# trimIt(DataBinder.Eval(Container.DataItem, "WebSalesText").ToString().SubString(0,250))%>

but this (dirty) solution would work:

<%# trimIt(DataBinder.Eval(Container.DataItem, "WebSalesText").ToString().
    SubString(0,Math.min(250,
    DataBinder.Eval(Container.DataItem, "WebSalesText").ToString().Length))
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM