Goal
Using the programming language of your choice, write the shortest program to eliminate comments from a string representing a C program.
Input
The string can be taken as any form of input, but it may also be taken as a variable.
Instructions
Two different kinds of comments are to be removed:
- multiline comments, starting with
/*
and ending with*/
- single line comments, starting with
//
and ending with Linux-style line breaks (LF,\n
)
Comments within strings are not to be deleted. For the purpose of this challenge, you only need to consider "
-delimited strings. In particular, you can ignore the possibility of '
-delimited character literals. You may also ignore trigraphs and line continuations (/\<LF>*...
).
Examples
Input:
#include <stdio.h>
int main(int argc, char** argv)
{
// this comment will be removed
if (argc > 1) {
printf("Too many arguments.\n"); // this too will be removed
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
// but not this
printf("just \"ano//ther\" test.");
return 0;
}
Output:
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc > 1) {
printf("Too many arguments.\n");
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
printf("just \"ano//ther\" test.");
return 0;
}
Input:
/*
this shall disappear
*/
#include <string>
int main(int argc, char** argv)
{
string foo = ""/*remove that!**/;
// Remove /* this
int butNotThis = 42;
// But do */ remove this
int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
return 0;//just a comment
}/*end of the file has been reached.*/
Output:
#include <string>
int main(int argc, char** argv)
{
string foo = "";
int butNotThis = 42;
int bar = 4 * 3;
return 0;
}
printf("\"/* This will stay too */\"\n");
appeared in the should become code? \$\endgroup\$// this comment will be removed
which just disappeared. Any rule for that? \$\endgroup\$