Comments are an important part of most code, however, in some circumstances, they
end up just taking up space, and bandwidth. Your task is to write a class
Comment with a method strip, which removes all the comments from a
piece of code. For this problem, we will consider only two type of comments:
comments starting with "//" and comments starting with "/*" and ending with
"*/". The first type of comments removes everything starting from "//" until
the end of the line. The second type of comment removes everything, starting
at "/*", until the sequence "*/" is found. In addition comments may not be
nested in any way. So, as soon as a "/*" comment is opened, everything is
commented, until a "*/" is found. Thus the String "/*//*/code", without
comments, is "code". Note that even though "//" is present, it does not
comment out code, because it is commented out itself, by the comment starting
with "/*". Similarly, the neither "//*" nor "///*" open a "/*" comment, because everything after the "//" is already commented out, and thus can not
start a comment.
However, it is not enough to simple search for the sequence "//" and "/*",
because these could be surrounded by quotes, and thus not a comment. For
example, in the code:
String s = "//";
"//" does not start a comment, because it is part of a String. A String begins
at a '"', which is not commented. A String ends at the first non-escaped '"'.
An escaped quote is one that is preceded by a '\'. Any time a backslash is
found, within a string, the next character is escaped, and the two of them
together make one character. For example, in java, c++, and c# "\n" represents
a new line, "\"" represents a quote, and "\\" represents a single '\'
(not two, because the first one escapes the second, and together they make one
Your method must take all of this into consideration when removing comments.
It must remove the rest of the line, when a "//" comment is found, and remove
characters starting with "/*" up to "*/" whenever a "/*" comment is found.
addition, it must take into account that characters which are part of a String,
cannot begin a comment (though they may end a comment which was previously
begun by "/*"). You will be given an input String, code, where each element
represents a line of code. Your method should remove all of the commented
parts of the code, and return the result. If, after removing commented text,
any of the lines have been entirely removed, your return should not contain
elements for those lines.
Upon finding "//" (not in a String) - remove the entire rest of the line.
Upon finding "/*" (not in a String) - remove all character until "*/"
Upon finding '"' (not in a comment) - all characters until the next unescaped
quote are part of a String, and can not start a comment.
Upon finding '\' (in a String) - the next character is escaped, and can not
close the String.