0

Program to count number of comments in code

This is an interesting problem, and a good interview question.

Count the number of comments in Code file

Lets define the comments :

1) Single line comments start with //

2) Multi line comments start with /* and end with */

What are the different possible comments in the code ?

// at the start of the line,

some code here and then // some code

“C://somepath” this is not a comment !! (Our code should be able to ignore this)

‘//’ Even this is not a comment we should ignore (//) here.

/* some line */

/* /**/*/

/*

//

//

*/

These are  some of the possible combinations that form comments in source code.

Now we can solve this using traditional approach of checking first character and second character and deciding based on that, but i dont like it,

it will involve lot of if’s and hard to keep track of all the conditions. Also the code will not be readable.

How about creating a state machine like the following :

WP_20140918_21_30_17_Pro

So we start with initial state “Normal Content” if we get a / there then we go to state -> Single Line Comment start , here if we get another /

we go to  state -> single line comment end. Similarly for the rest conditions.

And here is the code for above state machine :

Leave a comment if you like the post 🙂

 


Warning: count(): Parameter must be an array or an object that implements Countable in /home/algotu5/public_html/wp-includes/class-wp-comment-query.php on line 405