去除C代碼中的注釋,
1. 單行注釋//;
2. 多行注釋/**/;
3. 單行注釋以“/”結尾則下一行也為注釋;
4. 字符串中的注釋不處理。
說是C語言,但其實所有C語系的都可以,比如Java。
小工具:去除C語言注釋
int main(int argc, char* argv[]) {
enum {
literal,
single,
multiple,
string
} mode = literal;
char last = 0, current;
while ((current = getchar()) != EOF) {
switch (mode) {
case single: {
if (last != '//' && (current == '/n' || current == '/r')) {
putchar(current);
current = 0;
mode = literal;
}
} break;
case multiple: {
if (last == '*' && current == '/') {
current = 0;
mode = literal;
}
} break;
case string: {
if (last == '//') {
putchar(last);
putchar(current);
} else if (current != '//') {
putchar(current);
if (current == '"') {
mode = literal;
}
}
} break;
default: {
if (last == '/') {
if (current == '/') {
mode = single;
} else if (current == '*') {
mode = multiple;
} else {
putchar(last);
putchar(current);
}
} else if (current != '/') {
putchar(current);
if (current == '"') {
mode = string;
}
}
} break;
}
last = current;
}
return 0;
}
測試代碼
int main (int argc, char *argv[])
{
// not show/
not show/
not show
// not show
/* not show */
int is; // not show
int/* not show */ ms; /* not show */
double ds; // not show/
not show/
not show
double dm; /* ...
not show
not show */ float fs; /**
* now show
*/
float/**/ fm;
char cs[] = "aaa // /***/";
char cm1[] = /* not show */"hello*/";
char cm2[] = "/*redraiment"/* not show */;
/* printf("http://///"); */
return EXIT_SUCCESS;
}
處理后的代碼
int main (int argc, char *argv[])
{
int is;
int ms;
double ds;
double dm; float fs;
float fm;
char cs[] = "aaa // /***/";
char cm1[] = "hello*/";
char cm2[] = "/*redraiment";
return EXIT_SUCCESS;
}
新聞熱點
疑難解答
圖片精選