【发布时间】:2016-11-02 21:40:08
【问题描述】:
我正在编写一个接受用户评论的程序。特别是在/* 和*/ 之外以及内部都有输入。我已经编写了循环以在我的数组中找到字符 "/",但我不确定如何删除它以及它之间的所有内容,直到它再次出现。例如,如果我的输入是 "comment /* this is my comment */",我需要删除 /* */ 和它们之间的内容。所以我的输出就是"comment"。如果没有"/* and */",它不会删除任何东西。我知道我需要一个循环,但是我将如何编写一个循环来删除数组中的字符,直到下一个 "/" 出现并删除它?
我的代码如下:
#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;
}
【问题讨论】:
-
您只需要找到评论的开始和结束位置,然后使用这些位置进行子串和连接
-
这可能是一个细节,但使用 scanf() 读取您的输入将忽略第一个空格后面的所有内容(请参阅stackoverflow.com/questions/1247989/…)
-
@Christophe 谢谢,自从发帖以来我已经改成
fgets() -
return从函数返回,它不是“什么都不做”
标签: c arrays loops pointers char