<分区>
我正在尝试创建一个从字符串中删除 C 风格注释的函数。
我在使用指针遍历 char 数组时尝试使用经典的 while 循环,现在使用两个指针(p2
比 p1
领先一步,并且他们都从头开始)。我尝试检查 *p1 == '/' 和当 *p2 == '*'
时,当它是真的时,我会创建两个新的指针来找到注释的结尾(*p3 == '*' && *p4 == '/'
),然后我会创建两个新指针 p5
和 p6
,其中第一个指向 p1(注释中的第一个字符,应该是 '/',第二个指向 p4(将被删除的最后一个字符),我会使用 while 循环来尝试
执行 while(*p5++ = *p6++);
遗憾的是,这不起作用。
#include <stdio.h>
void remove_comments(char* s) {
char *p1=s;
char *p2 = s;
p2++; // move p2 ahead of p1;
while(*p1 !='\0' && *p2 !='\0') {
if(*p1=='/' && *p2=='*') { // beginning of comment
char *p3 = p1; // save their positions and
char *p4 = p2; //create two new pointers
while(*p3 !='\0' && *p4 !='\0') {
if(*p3 == '*' && *p4 == '/') { //if end of comment
char *p5 = p1;
char *p6 = p4;
while(*p5++ = *p6++);
} else p1++;
p3++;
p4++;
}
}
p1++;
p2++;
}
}
int main() {
char arr[] = "This is an /*this is a comment*/ example!";
remove_comments(arr);
printf("%s", arr);
return 0;
}
上面的代码应该产生输出 This is an example!
,但字符串保持不变。我该如何解决这个问题?