C# HTML字符串 -> 获取不带HTML标签的长度

5

我有一个包含HTML图片的字符串,例如:

string str = "There is some nice <img alt='img1' src='img/img1.png' /> images in this <img alt='img2' src='img/img2.png' /> string. I would like to ask you <img alt='img3' src='img/img3.png' /> how Can I can I get the Lenght of the string?";

我希望获取字符串的长度,但不包括图片,并计算图片的数量。因此,结果应为:
int strLenght = 111;
int imagesCount= 3;

请问您能展示一下最有效的方式吗?

谢谢


你可以借助于正则表达式来完成这个任务。如果需要基于此解决方案,请告诉我。 - K D
请查看以下答案,以去除HTML标签:https://dev59.com/wWMl5IYBdhLWcg3wwZIq#18154046 随后您将能够获取字符串长度。 - ADreNaLiNe-DJ
1
你最好的选择是使用像Html Agility Pack这样的HTML解析器,这样你就可以正确地计算内容的字符长度和图像标签的数量。 - juharr
5个回答

4
我建议使用真正的HTML解析器,例如HtmlAgilityPack。然后就很简单了:
string html = "There is some nice <img alt='img1' src='img/img1.png' /> images in this <img alt='img2' src='img/img2.png' /> string. I would like to ask you <img alt='img3' src='img/img3.png' /> how Can I can I get the Lenght of the string?";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
int length = doc.DocumentNode.InnerText.Length;               // 114
int imageCount = doc.DocumentNode.Descendants("img").Count(); // 3

这是您示例中 DocumentNode.InnerText 返回的内容,您跳过了一些空格:
There is some nice  images in this  string. I would like to ask you  how Can I can I get the Lenght of the string?

2
我有一个类似的问题,并创建了这个方法。您可以使用它来去除HTML标签并计算字符串。
public static string StripHtmlTags(string source)
{
  if (string.IsNullOrEmpty(source))
  {
    return string.Empty;
  }

  var array = new char[source.Length];
  int arrayIndex = 0;
  bool inside = false;
  for (int i = 0; i < source.Length; i++)
  {
    char let = source[i];
    if (let == '<')
    {
      inside = true;
      continue;
    }

    if (let == '>')
    {
      inside = false;
      continue;
    }

    if (!inside)
    {
      array[arrayIndex] = let;
      arrayIndex++;
    }
  }

  return new string(array, 0, arrayIndex);
}

你的计数将会是这样的:
int strLength = StripHtmlTags(str).Count;

你知道你可以直接使用 foreach(char let in source),因为 string 实现了 IEnumerable<char> 接口。 - juharr

2

添加一个(COM)引用到MSHTML(Microsoft HTML对象库),然后你就可以:

var doc = (IHTMLDocument2)new HTMLDocument();
doc.write(str);

Console.WriteLine("Length: {0}", doc.body.innerText.Length);
Console.WriteLine("Images: {0}", doc.images.length);

1
如果您想使用我在上面评论中提到的 RegularExpression 进行操作,请使用以下代码。
var regex = new System.Text.RegularExpressions.Regex("<img[^>]*/>");
var plainString = regex.Replace(str, ""); 

// plainString.length will be string length without images
    var cnt = regex.Matches(str).Count; // cnt will be number of images

0

我喜欢John Smith的解决方案,但是我不得不在末尾添加Trim()以匹配MS Word的结果。

使用这个:

return new string(array, 0, arrayIndex).Trim();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接