C 面试编程问题,我需要匹配两个 HTML 格式字符串中存在的文本。
这是两个示例字符串
<html><p>Hello</p></html>
<html><p><b>H</b>ello</p></html>
想要讨论最好的方法,这是我最初的思考过程
- 从给定字符串中删除 HTML 标签
void remove_html(char* str) {
char* html_str = str;
while(*str) {
if(*html_str == '<')
while(*html_str && *html_str++ != '>');
*str++ = *html_str++;
}
}
- 提取字符串后,我们就可以匹配它们。
谢谢!
最佳答案
如果我正确地收集了您的要求,我认为编写一个跳过 XML 标签来获取实际文本的函数会更简单。然后将其用作普通循环中的步骤函数:
char const* skip_html(char const *str)
{
if(!str)
return NULL;
while(*str && *str == '<') {
// Must be a loop, to skip consecutive tags
while (*str && *str++ != '>')
; // No-op. Increment in the loop condition
// Here str points past the '>' or at the end.
}
return str;
}
// Must be passed valid string pointers, otherwise the behavior is undefined
bool compare_string_with_embedded_html(char const *lhs, char const *rhs) {
for (lhs = skip_html(lhs), rhs = skip_html(rhs);
*lhs && *rhs;
lhs = skip_html(++lhs), rhs = skip_html(++rhs)) {
if (*lhs != *rhs)
return false;
}
return *lhs == *rhs; // True only if both point at the end of each respective
// string.
}
如果您确实关心 HTML 的结构,那么这将不起作用。您需要一个合适的解析器。
关于html - 如何在C中匹配两个HTML之间的文本数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885510/