字符计数减去HTML字符C#
我试图找出一种方法来计算字符串中的字符数,截断字符串,然后返回它。但是,我需要这个函数来不计算HTML标记。问题是,如果对HTML标记进行计数,那么如果截断点位于标签的中间,则页面将出现断裂。 这就是我目前所拥有的字符计数减去HTML字符C#,c#,truncate,counting,html,C#,Truncate,Counting,Html,我试图找出一种方法来计算字符串中的字符数,截断字符串,然后返回它。但是,我需要这个函数来不计算HTML标记。问题是,如果对HTML标记进行计数,那么如果截断点位于标签的中间,则页面将出现断裂。 这就是我目前所拥有的 public string Truncate(string input, int characterLimit, string currID) { string output = input; // Check if the string is longer tha
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;
}
公共字符串截断(字符串输入、int字符限制、字符串currID){
字符串输出=输入;
//检查字符串是否超过允许的长度
//否则什么也不做
if(output.Length>characterLimit&&characterLimit>0){
//将字符串减少到最大字符数
输出=输出。子字符串(0,characterLimit);
//检查截断点后面的字符是否为空格
如果不是,我们正处于一个词的中间,需要去掉其余部分。
if(input.Substring(output.Length,1)!=“”){
int LastSpace=output.LastIndexOf(“”);
//如果我们找到了一个空间,就缩减到那个空间
if(LastSpace!=-1)
{
output=output.Substring(0,LastSpace);
}
}
//结束任何锚
if(output.Contains(“”);
}
返回输出;
}
但我对此并不满意。有没有更好的方法呢?如果你能提供一个新的解决方案,或者是关于我目前所拥有的内容的建议,那就太好了
免责声明:我从未使用过C#,因此我不熟悉与该语言相关的概念……我这样做是因为我必须这样做,而不是出于选择
谢谢,
Hristo使用正确的工具解决问题。 HTML并不是一种简单的解析格式。我建议您使用XML解析器,而不是使用自己的。如果您知道您将只解析XHTML,那么您可以使用XML解析器 这些是在HTML上执行操作的唯一可靠方法,可以保留语义表示
不要尝试使用正则表达式。HTML不是一种正则语言,朝这个方向发展只会给自己带来痛苦。你应该使用实际的。这是在HTML上执行操作的唯一可靠方法,可以保留语义表示。也不要忘了字符实体:
,和8212,等。你不想打破中间的。谢谢你的建议。我看了解析器,使用它看起来不太微不足道。我唯一反对语法分析器的是,我不想解析整个HTML文档…只是一个将被动态添加到页面上的片段。@nt.SelectNodes
方法。您应该能够选择所有类型的所有节点,然后使用InnerText
属性来计算非HTML字符的数量…在我可以使用任何HTML agility pack功能(如DocumentElement.SelectNodes
)之前,我需要让它与Microsoft Visual Web Developer一起工作。是否你对如何“安装”它有什么建议吗?