0

我试图找出一种方法来计算字符串中的字符数,截断字符串,然后返回它。但是,我需要这个函数来不计算 HTML 标签。问题是如果它计算 HTML 标签,那么如果截断点在标签的中间,那么页面就会出现损坏。

这是我目前所拥有的......

public string Truncate(string input, int characterLimit, string currID) {
    string output = input;

    // Check if the string is longer than the allowed amount
    // otherwise do nothing
    if (output.Length > characterLimit && characterLimit > 0) {

        // cut the string down to the maximum number of characters
        output = output.Substring(0, characterLimit);

        // Check if the character right after the truncate point was a space
        // if not, we are in the middle of a word and need to remove the rest of it
        if (input.Substring(output.Length, 1) != " ") {
            int LastSpace = output.LastIndexOf(" ");

            // if we found a space then, cut back to that space
            if (LastSpace != -1)
            {
                output = output.Substring(0, LastSpace);
            }
        }
        // end any anchors
        if (output.Contains("<a href")) {
            output += "</a>";
        }
        // Finally, add the "..." and end the paragraph
        output += "<br /><br />...<a href='Announcements.aspx?ID=" + currID + "'>see more</a></p>";
    }
    return output;
}

但我对此并不满意。有一个更好的方法吗?如果您可以为此提供一个新的解决方案,或者就我目前所拥有的内容提供一些建议,那就太好了。

免责声明:我从未使用过 C#,所以我不熟悉与该语言相关的概念……我这样做是因为我必须这样做,而不是出于选择。

谢谢, 赫里斯托

4

1 回答 1

3

使用正确的工具解决问题。

HTML 不是一种简单的解析格式。我建议您使用经过验证的现有解析器,而不是自己滚动。如果您知道您只会解析 XHTML - 那么您可以使用 XML 解析器。

这些是在 HTML 上执行将保留语义表示的操作的唯一可靠方法。

不要尝试使用正则表达式。HTML 不是一种常规语言,你只会让自己在那个方向上感到悲伤和痛苦。

于 2010-10-08T14:53:22.550 回答