gpt4 book ai didi

C# HTML 字符串 -> 获取没有 html 的长度

转载 作者:太空狗 更新时间:2023-10-30 00:30:25 25 4
gpt4 key购买 nike

我有带有 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;

能告诉我最有效的方法吗?

谢谢

最佳答案

我建议使用真正的 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?

关于C# HTML 字符串 -> 获取没有 html 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com