【问题标题】:Removing text after character c删除字符 c 之后的文本
【发布时间】:2013-04-10 18:09:24
【问题描述】:

我有一些看起来像这样的文本,来自输入文件:

func:
    sll  $t3, $t4, 5       # t1 = (i * 4)
    add  $t3, $a1, $t4     # t2 contains address of array[i]
    sw   $t1, 4($t2)       # array[i] = i
    addi $t2, $t5, 3       # i = i+1

我想“清理”它,并将其输出到另一个文件,如下所示:

func:
    sll  $t3, $t4, 5
    add  $t3, $a1, $t4
    sw   $t1, 4($t2)
    addi $t2, $t5, 3

这是我用来执行此操作的代码块:

    while(fgets(line, 100, input) != NULL)
   {
    int comment = 0;
    for(int x = 0; x < 100; x++)
    {
        if(line[x] == '#')
            comment = 1;

        if(comment == 1)
            line[x] = '\0'; //I know this is incorrect
    }
    fprintf(cleaned, "%s", line);
   }

如何更改该代码块以使其按我的意愿工作?我搞砸了,用 '\n' '\0' 和 " " 尝试了一些东西,但都没有奏效。

提前致谢!

【问题讨论】:

    标签: c text input output stdio


    【解决方案1】:

    您可以使用strchr 在您的行中查找“#”。如果找到,则返回一个指针,如果没有则返回 NULL
    您可以确定开始和出现之间的差异并创建一个新字符串。

    /* strchr example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
        char str[] = "This is a sample string";
        char * pch;
        printf ("Looking for the 's' character in \"%s\"...\n",str);
        pch=strchr(str,'s');
        while (pch!=NULL)
          {
            printf ("found at %d\n",pch-str+1);
            pch=strchr(pch+1,'s');
          }
        return 0;
    }
    

    参考here

    【讨论】:

      【解决方案2】:

      您可以这样做,但您不需要设置标志。您可以立即截断该行并使用break; 停止任何进一步搜索

      for(int x = 0; x < 100; x++)
      {
          if(line[x] == '#') {
              line[x] = '\n';
              line[x + 1] = '\0';
              break;
          }
      }
      

      【讨论】:

        【解决方案3】:

        在调试器中运行这段代码,看看它到底在做什么。可能在您的外部 while 循环中放置一个断点,并一次遍历一个字符以精确理解行为。您可能会很清楚下一步该做什么。

        如果在 unix 上使用 gdb,请使用 -g 编译您的程序以包含调试信息,然后在 Google 上搜索“gdb cheatsheet”之类的内容以开始使用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多