html - 如何在C中匹配两个HTML之间的文本数据

标签 html c

C 面试编程问题,我需要匹配两个 HTML 格式字符串中存在的文本。

这是两个示例字符串

<html><p>Hello</p></html>

<html><p><b>H</b>ello</p></html>

想要讨论最好的方法,这是我最初的思考过程

  1. 从给定字符串中删除 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/

    相关文章:

    javascript - 如何生成完全不包含任何空格甚至在字符串开头或结尾处不包含空格的正则表达式

    c - 如何用表格制作 "global variable"?

    c - 父进程等待所有子进程完成后再继续

    c++ - 从 c++/c 中的函数返回的问题

    c - 用 libgit2 实现 'git pull'?

    javascript - 鼠标悬停更改图像

    php - 使用 php 在标签内查找名称属性

    c - 读取/proc/pid/mem 文件不返回任何内容

    php - 将用户配置文件详细信息更新到 MySQL

    javascript - 如何从 DOM 错误事件中获取详细消息