如果单词比X长,则用点替换字符串的结尾

时间:2013-05-27 01:35:44

标签: c# asp.net-mvc razor

如果Razor CSHTML页面中的字符串比X字符更长,我怎样才能格式化字符串:

<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

感谢。

4 个答案:

答案 0 :(得分:6)

任何字符串。 See here

代码......

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

答案 1 :(得分:5)

这是您可以使用的辅助方法:

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>

答案 2 :(得分:1)

Model.Console.Length <= 9 ? Model.Console : Model.Console.Substring(0, 9) + "...";

这是使用Tirany Operator

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

你可以在你的剃刀代码中直接放入此内容,而不必从视图中调用任何代码。

注意 - 如果Model.Console为空或空

,这可能会中断

答案 3 :(得分:1)

正如一个选项,一个Regex.Replace(虽然它可能更容易使它成为一个函数并使用常规Substring

Regex.Replace("Vila Real de Santo António", "^(.{9}).+", "$1...")
相关问题