簡體   English   中英

字符串中的字符數限制

[英]Limit of characters in string

我有一個帶有一些字符串的文本框。 這個字符串可能很長。 我想限制顯示的文本(例如10個字符)並附加3個點,如:

如果文本框取值“成為或不成為,那就是問題:”它只顯示“要成為,或......”

要么

如果文本框取值“待”,則顯示“待定”

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

您應該使用Label控件來顯示數據。 AutoSize設置為false,將AutoEllipsis為true。 為什么有一個文本框具備此功能,其中原因在於:

  • 你要在哪里存儲截斷的數據?
  • 如果用戶選擇要編輯甚至復制的文本,您如何處理?

如果你反駁的是TextBox是只讀的,那么這只是重新考慮你正在使用的控件的更多理由。

嘗試這個:

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

如果您需要使用正則表達式,您可以這樣做:

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

這將使用三個點替換第十個字符后的任何文本。

(?<=expr)是一個外觀 這意味着expr必須匹配(但不消耗)才能使匹配的其余部分成功。 如果輸入中的字符少於10個,則不執行替換。

這是關於ideone演示

像這樣的東西?

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

顯示您嘗試過的內容以及您遇到的問題。

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

您不需要使用regex

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM