Comments can be vital in the readability and documentation of code. It enables developers to provide explanations inside their code. However, when processing code for various purposes, such as analysis or formatting, comments can become an obstacle. In this Answer, we’ll demonstrate how to remove comments from code efficiently.
The C++ code given below removes comments from the source code provided in its parameters. The commentsremoval
function removes comments from a given array of strings representing the code. It iterates through each line, character by character, and tracks whether it’s inside a comment. After execution, it returns the code with the comments removed.
Note: For this problem, we only check for comments that begin with
//
.
vector<string> commentsremoval(vector<string>& source) {vector<string> output;bool comment = false;string curr = "";for (const string& line : source) {for (int i = 0; i < line.size(); ++i) {if (!comment && i + 1 < line.size() && line[i] == '/' && line[i + 1] == '/') {break;} else if (!comment && i + 1 < line.size() && line[i] == '/' && line[i + 1] == '*') {comment = true;i++;} else if (comment && i + 1 < line.size() && line[i] == '*' && line[i + 1] == '/') {comment = false;i++;} else if (!comment) {curr += line[i];}}if (!comment && !curr.empty()) {output.push_back(curr);curr = "";}}return output;}int main() {vector<string> code = {"int main() {"," int a;","// This is a comment","}"};vector<string> output = commentsremoval(code);for (const string& line : output) {cout << line << endl;}}
The code can be explained below:
Line 1: The commentremoval
function takes a vector of strings source
representing the source code to remove comments from.
Line 2: We define output
which stores the code without comments that we’ll return at the end.
Line 5: We define curr
, which is a string accumulator to build the current line of code.
Lines 7–8: We iterate through each line of the code, and then, for each line, we iterate through each character.
Lines 9–20: The steps to remove comments in the code are:
If we’re not inside a comment and encounter a double slash, we break out of the loop.
If we’re not inside a comment and we find a forward slash followed by an asterisk, we set comment
to true
and increments i
to skip the asterisk.
If we’re inside a comment and we find an asterisk followed by a forward slash, we set comment
to false
and increments i
to skip the forward slash character.
If none of the above conditions are met, it appends the character to curr
.
Lines 22–25: If we’re not in a comment and curr
is not empty, we add curr
to the output
vector and reset curr
for the next line.
Lines 31–43: This is the main
function to test this code.
Note: You can change the inputs in the
main
function to test other inputs.
Free Resources