使用C++移除字串中的註釋
給定一個C++程式作為輸入,從中刪除註釋。'source'是一個向量,其中第i行原始碼是source[i]。這表示透過換行符'\n'分割原始碼字串的結果。在C++中,我們可以建立兩種型別的註釋,即行註釋和塊註釋。
字串'//'表示行註釋,這意味著它右側的字串將被程式忽略。
字串'/*'和'*/'是多行註釋,表示從'/*'到'*/'之間的字串將被忽略。
第一個有效的註釋優先於其他註釋:如果字串'//'出現在塊註釋中,則會被忽略。類似地,如果字串'/*'出現在行註釋或塊註釋中,也會被忽略。如果刪除註釋後某一行程式碼為空,則不應輸出該行——答案列表中的每個字串都將是非空的。
例如:
輸入1:
source = ["/*Test program */", "int main()", "{ ", " // variable
declaration ", "int a, b, c;", "/* This is a test", " multiline ", "
comment for ", " testing */", "a = b + c;", "}"]
The line by line code is as follows:
/*Test program */
int main(){
// variable declaration
int a, b, c;
/* This is a test multiline comment for testing */
a = b + c;
}輸出:
["int main()","{ "," ","int a, b, c;","a = b + c;","}"]The line by line
code is as follows:
int main() /// Main Function
{
int a, b, c;
a = b + c;
}解釋:字串'/*'表示多行註釋,包括第1行和第6-9行。字串'//'表示第4行為註釋。
解決這個問題的方法
我們將像理想的編譯器那樣逐行解析字串。當我們遇到'//'或'/*'時,我們將忽略這些塊引用之間和之後的所有字元。
函式removeString(vector<string>&source)接收原始碼作為輸入,並返回刪除註釋後的程式碼。
布林變數comment初始化為false,它將檢查特定字串塊或字元是否為註釋。
如果我們開始一個塊註釋並且我們不在塊中,那麼我們將跳過接下來的兩個字元並改變我們在這個特定塊中的狀態。
如果我們結束一個塊註釋並且我們在這個塊中,我們將跳過接下來的兩個字元並將狀態更改為不在塊中。
如果我們開始一個行註釋並且不在塊中,我們將忽略該行的其餘部分。
如果我們不在塊註釋中(並且它不是註釋的開始),我們將記錄我們所在的字元。
如果我們不在每一行結束時的塊中,我們將記錄該行。
該演算法的時間複雜度為O(source)。source是輸入字串。
示例
#include<bits/stdc++.h>
using namespace std;
vector<string>removeComments(vector<string>&source){
vector<string>ans;
string s;
bool comment= false;
for(int i = 0; i < source.size(); i++) {
for(int j = 0; j < source[i].size(); j++) {
if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='/')
break;
else if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='*')
comment = true;
j++;
else if(comment && j + 1 < source[i].size() && source[i][j] == '*' && source[i][j+1]=='/')
comment = false;
j++;
else if(!comment)
s.push_back(source[i][j]);
}
if(!comment && s.size()) ans.push_back(s), s.clear();
}
return ans;
}
int main(){
vector<string>source
(“ source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
The formatted code can be interpreted as -
/*Test program */
int main() // Main function{
int a, b, c; // variable declaration
/* This is a test multiline comment for testing */
a = b + c;
}”);
vector<string>res= removeComments(source);
for(auto x:res){
cout<<x;
}
return 0;
}輸出
["int main()","{ "," ","int a, b, c;","a = b + c;","}"]The line by line
code is visualized as below:
int main(){
int a, b, c;
a = b + c;
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP