C指针算术数组删除字符

标签 c arrays loops pointers char

我正在编写一个接受用户评论的程序。特别是在 /**/ 以及内部输入的输入。我已经编写了循环以在我的数组中找到 char "/",但我不确定如何删除它以及它之间的所有内容,直到它再次出现。例如,如果我的输入是 "comment/* this is my comment */" 我需要删除 /* */ 和之间的内容.所以我的输出只是"comment"。如果没有 "/* 和 */",它不会删除任何内容。我知道我需要一个循环,但我将如何编写一个循环来删除数组中的字符,直到下一个 "/" 出现并将其删除? 我的代码如下:

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

void remove_comment(char *s1, char *s2){

  for(; *s1 != '\0'; s1++){  //loops through array until null value
    if(*s1 == '/'){  //if array has '/' stored
                     //clear array elements till next '/' and removes it as well
  }
    else{
    return; //do nothing to array
  }
  strcpy(s2,s1); //copies new modified string to s2 for later use
}

int main(){

  char s1[101]; //declares arrays up to 100 in length with room for null character
  char s2[101];

  printf("Enter a comment: "); //enter a comment
  fgets(s1, 100, stdin);  // saves comment to array

  remove_comment(s1,s2);  //calls function

  printf("%s", s2); //prints my modified array 

  return 0;
}

最佳答案

您的代码似乎建立在探索字符串字符的循环之上。因此,我建议您采用以下解决方案:

void remove_comment(char *s1, char *s2) 
{
    for(int in_comment=0; *s1 ; s1++){  //loops through array until null value
      if(!in_comment && *s1 == '/' && s1[1]=='*') {  //if array has '/' follewed by '*' stored
          in_comment=1;    // we enter a comment area
          s1++; 
      }
      else if (in_comment) {     // if we are in a comment area
          if (*s1=='*' && s1[1]=='/') {    // we only look for end of comment
              in_comment = 0; 
              s1++;
          }
      }
      else *s2++=*s1;       // if we're not in comment, in all other cases we just copy current char
    }
    *s2='\0'; // don't forget to end the string. 
}

它使用 in_comment 变量来判断我们当前是否正在探索评论中的字符(并寻找评论的结尾)或不(并最终寻找评论的开始)。

它使用*s1s1[1] 来访问当前和下一个字符。

它保留原始字符串不变。

Online demo

关于C指针算术数组删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38129098/

相关文章:

c - Linux 和 Windows 上的报警功能 -> 找不到 Windows 的等效功能 -> C

c - 程序中出现 '\222'

c - 请解释以下 C 程序的输出。

C:复制结构/数组元素

css - 在 Sass 中循环 @for 如何正确使用 $#{value}#{$i}?

c - 如何将4个字节的char缓冲区复制到long中

c - Libelf 会创建损坏的输出文件,即使什么都不做

arrays - Postgresql - 在大数据库中使用数组的性能

c - 在 c99 模式之外循环静态分配的数组?

java - 列出素数