字符串中的字符数限制

时间:2013-05-15 10:45:28

标签: c# regex devexpress maskedtextbox maskedinput

我的文本框带有一些字符串。这个字符串可能很长。我想限制显示的文本(例如10个字符)并附加3个点,如:

如果文本框取值“成为或不成为,那就是问题:”它只显示“要成为,或......”

或者

如果文本框的值为“待定”,则显示“待定”

            Html.DevExpress().TextBox(
                    tbsettings =>
                    {
                        tbsettings.Name = "tbNameEdit";;
                        tbsettings.Width = 400;
                        tbsettings.Properties.DisplayFormatString=???
                    }).Bind(DataBinder.Eval(product, "ReportName")).GetHtml();

7 个答案:

答案 0 :(得分:4)

您应该使用Label控件来显示数据。将AutoSize设置为false,将AutoEllipsis设置为true。 TextBox 具有此功能的原因很充分,其中包括:

  • 您要在哪里存储截断的数据?
  • 如果用户选择要编辑或甚至复制的文本,您如何处理?

如果你反驳的是TextBox是只读的,那么这只是重新考虑你正在使用的控件的更多理由。

答案 1 :(得分:2)

试试这个:

string displayValue = !string.IsNullOrWhiteSpace(textBox.Text) && textBox.Text.Length > 10
    ? textBox.Text.Left(10) + "..."
    : textBox.Text;

在扩展方法中:

public static string Ellipsis(this string str, int TotalWidth, string Ellipsis = "...")     
{
    string output = "";

    if (!string.IsNullOrWhiteSpace(str) && str.Length > TotalWidth)
    {
        output = output.Left(TotalWidth) + Ellipsis;
    }

    return output;
}

使用它将是:

string displayValue = textBox.Text.Ellipsis(10);

答案 2 :(得分:2)

如果您需要使用正则表达式,可以执行以下操作:

Regex.Replace(input, "(?<=^.{10}).*", "...");

这将用第三个字符替换第三个字符后面的任何文字。

(?<=expr) lookbehind 。这意味着expr必须匹配(但不消耗)才能使匹配的其余部分成功。如果输入中的字符少于10个,则不执行替换。

这是demo on ideone

答案 3 :(得分:1)

这样的东西?

static void SetTextWithLimit(this TextBox textBox, string text, int limit)
{
    if (text.Length > limit)
    {
        text = text.SubString(0, limit) + "...";
    }
    textBox.Text = text;
}

显示您尝试过的内容以及您遇到的问题。

答案 4 :(得分:1)

string textToDisplay = (inputText.Length <= 10) 
          ? inputText
          : inputText.Substring(0, 10) + "...";

答案 5 :(得分:0)

您无需使用regex

string s = "To be, or not to be, that is the question:";
s = s.Length > 10 ? s.Remove(10, s.Length - 10) + "..." : s;

答案 6 :(得分:0)

string maxStringLength = 10;
string displayStr = "A very very long string that you want to shorten";
if (displayStr.Length >= maxStringLength) {
    displayStr = displayStr.Substring(0, maxStringLength) + " ...";
}

//displayStr = "A very very long str ..."