思路
模拟。括号匹配思想。
由于注释可以嵌套,我们可以维护一个变量去记录嵌套的层数:
- 当遇到
/*时,就说明进入了新的一层注释。 - 当遇到
*/时,如果当前处于注释内部,说明最内层的一层注释结束了。 - 对于其他普通字符,如果当前在注释外部,直接输出即可;否则就忽略。
注意输入中可能用空格,所以可以用 getline 读入。
一些细节可以看一下代码部分。
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
int lvl;
string s;
signed main() {
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cout<<"Case #1:\n";
while (getline(cin,s)) {
int i=0;
int len=s.length();
while (i<len) {
if (i+1<len && s[i]=='/' && s[i+1]=='*') lvl++,i+=2;
else if (lvl>0 && i+1<len && s[i]=='*' && s[i+1]=='/') lvl--,i+=2;
else {
if (lvl==0) cout<<s[i];
i++;
}
}
if (lvl==0) cout<<'\n';
}
return 0;
}