【问题标题】:Is there a way to extract a comment out of a C string?有没有办法从 C 字符串中提取注释?
【发布时间】:2022-01-14 08:44:04
【问题描述】:

我正在尝试编写一个从字符串中提取注释的函数。例如,给定:

"this is a test //bread is great"

它返回:

"bread is great"

我尝试计算字符数,直到出现第一个“//”,然后修剪字符串中不需要的部分。

while(s[i] != '/' && s[i+1] != '/') {
    newbase++;
    i++;
}

它适用于第一个示例,但如果给我这样的字符串,我会遇到问题:

"int test = 2/3"

它应该返回""(一个空字符串),但它没有。没看懂。

【问题讨论】:

  • &&不应该是||吗?
  • 你可以先用strchr查看字符串是否包含//
  • 如果在找到模式之前遇到字符串结尾,则应停止搜索。
  • 可以使用strstr
  • 假设输入字符串是"Text // Comment\nMore Information"——其中有多少被视为“评论”?对于 C 编译器,只有“注释”才算作注释;您的代码似乎也可能包含“更多信息”。这取决于问题规范的要求。顺便说一句,对于 C 编译器来说,整个 "/\\\n\\\n/\\\nComment\n" 是一个注释。

标签: c


【解决方案1】:

这是非常基本的字符串处理。只需使用strstr,如果成功,则使用结果。可选择将其复制到第二个字符串。

#include <stdio.h>
#include <string.h>

int main (void)
{
  const char* str = "this is a test //bread is great";
  const char* result = strstr(str,"//");

  if(result != NULL)
  {
    result += 2; // skip the // characters
    puts(result); // print the string
    
    // optionally make a hardcopy
    char some_other_str[128];
    strcpy(some_other_str, result);
    puts(some_other_str);
  }
}

【讨论】:

    【解决方案2】:

    如果您只想在第一次出现 "//" 后天真地提取剩余的字符串,您可能需要这样的东西:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      const char *text = "this is a test //bread is great";
      const char* commentstart = strstr(text, "//");
    
      char comment[100] = { 0 }; // naively assume comments are shorter then 99 chars
    
      if (commentstart != NULL)
      {
        strcpy(comment, commentstart + 2);
      }
    
      printf("Comment = \"%s\"", comment);
    }
    

    免责声明:

    • 这是未经测试的简单代码,显示了一种可能的方法。没有任何错误检查,特别是如果评论超过 99 个字符,就会出现缓冲区溢出。
    • 此代码绝对不适合从现实生活中的 C 代码中提取 cmets。

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2021-05-15
      • 2020-04-08
      • 2021-10-04
      • 2022-12-11
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多