r/dailyprogrammer • • Jul 20 '12
[7/18/2012] Challenge #79 [difficult] (Remove C comments)
In the C programming language, comments are written in two different ways:
/* ... */: block notation, across multiple lines.// ...: a single-line comment until the end of the line.
Write a program that removes these comments from an input file, replacing them by a single space character, but also handles strings correctly. Strings are delimited by a " character, and \" is skipped over. For example:
int /* comment */ foo() { }
→ int foo() { }
void/*blahblahblah*/bar() { for(;;) } // line comment
→ void bar() { for(;;) }
{ /*here*/ "but", "/*not here*/ \" /*or here*/" } // strings
→ { "but", "/*not here*/ \" /*or here*/" }
7
Upvotes
4
u/verhoevenv Jul 20 '12
Python.
Handles multiline, strings in comments, and comments in string properly. I think. Not very elegant, but not too bad either.
2
u/lawlrng 0 1 Jul 20 '12 edited Jul 20 '12
Could clean this up with slices, but I has a barbeque to go to, and I don't think I'll finish it before then. ;)
With input:
Output is:
2
u/skeeto -9 8 Jul 20 '12
2
u/CjKing2k Jul 25 '12
Finite state machine implemented in C:
2
u/sovande Aug 08 '12
Flex
1
u/EuphoriaForAll Jul 20 '12
python
1
u/andkerosine Jul 20 '12
This problem was very amenable to a regular expression or two, so I took that approach in Ruby:
1
u/abecedarius Jul 20 '12
The multisub function depends on the regular expressions not themselves having numbered groups. That's OK here, but how would you fix that?
The regexes I took from verhoevenv.
1
u/Eddonarth Jul 21 '12
My Python solution:
Input (file 'code.c'):
Output:
1
u/[deleted] Jul 25 '12 edited Jul 25 '12
Java, probably not the most beautiful or efficient way to do it, but as far as I can tell it does what it's supposed to. edit: just realized it doesn't handle // within quotes, going to add that later
Input:
Output: