gpt4 book ai didi

c - 从 C 样式字符串问题中删除 C 样式注释的函数

转载 作者:太空狗 更新时间:2023-10-29 15:39:45 27 4
gpt4 key购买 nike

<分区>

我正在尝试创建一个从字符串中删除 C 风格注释的函数。

我在使用指针遍历 char 数组时尝试使用经典的 while 循环,现在使用两个指针(p2p1 领先一步,并且他们都从头开始)。我尝试检查 *p1 == '/' 和当 *p2 == '*' 时,当它是真的时,我会创建两个新的指针来找到注释的结尾(*p3 == '*' && *p4 == '/'),然后我会创建两个新指针 p5p6 ,其中第一个指向 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!,但字符串保持不变。我该如何解决这个问题?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com