简体   繁体   English

限制c#字符串中的字符数

[英]Limit Character count in c# String

I have this code, is there an easy way to limit the amount of characters displayed to 250? 我有这段代码,有没有一种简单的方法可以将显示的字符数限制为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? 您是否正在寻找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.: 这不起作用,因为SubString对于少于250个符号的字符串将失败。

<%# 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))
%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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