代码之家  ›  专栏  ›  技术社区  ›  Hristo

字符数减去HTML字符c#

  •  0
  • Hristo  · 技术社区  · 15 年前

    我试图找出一种方法来计算字符串中的字符数,截断字符串,然后返回它。但是,我需要这个函数来不计算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,所以我不熟悉与语言相关的概念…我这么做是因为我必须这么做,不是因为我的选择。

    谢谢, 希斯托

    1 回复  |  直到 10 年前
        1
  •  3
  •   LBushkin    15 年前
    推荐文章