若单词比X长,则用点替换字符串末尾

本文关键字:替换 字符串 单词比 | 更新日期: 2023-09-27 18:15:33

如果字符串比X个字符长,我如何在Razor CSHTML页面中格式化字符串:

<p>@Model.Council</p> 
Example for an X = 9
-> if Council is "Lisbon", then the result is "<p>Lisbon</p>"
-> if Council is "Vila Real de Santo António", then the result is "<p>Vila Real...</p>" with the title over the <p> "Vila Real de Santo António" showing the complete information

谢谢。

若单词比X长,则用点替换字符串末尾

用于任何字符串。请参见此处。

对于您的代码。。。

@(Model.Council.Length>10 ? Model.Council.Substring(0, 10)+"..." : Model.Council)

这里有一个可以使用的辅助方法:

public static class StringHelper
{
    //Truncates a string to be no longer than a certain length
    public static string TruncateWithEllipsis(string s, int length)
    {
        //there may be a more appropiate unicode character for this
        const string Ellipsis = "...";
        if (Ellipsis.Length > length)
            throw new ArgumentOutOfRangeException("length", length, "length must be at least as long as ellipsis.");
        if (s.Length > length)
            return s.Substring(0, length - Ellipsis.Length) + Ellipsis;
        else
            return s;
    }
}

只需从CSHTML:内部调用即可

<p>@StringHelper.TruncateWithEllipsis(Model.Council, 10)</p>

作为一个选项,Regex.Replace(尽管将其作为一个函数并使用常规Substring可能更容易(

Regex.Replace("Vila Real de Santo António", "^(.{9}).+", "$1...")
Model.Console.Length <= 9 ? Model.Console : Model.Console.Substring(0, 9) + "...";

这是使用蒂拉尼操作员

它检查长度是否小于或等于9,如果是,则在?之后使用左侧,如果为false,则使用右侧,它将截断9个字符后的字符串并附加"..."

您可以将这一点直接放在您的剃刀代码中,而不必从视图中调用任何代码。

注意-如果Model.Console为空或为空,则可能会中断