Remove Nested Comments.

来源:互联网 发布:三只松鼠 淘宝 编辑:程序博客网 时间:2024/06/06 09:05

Comments can be single line using //, or multiple line using /* */

We can use two flags to make the begin and end of two types of comments.

string removeComments(string str) {  string res;  bool s_comment = false;  bool m_comment = false;  int n = str.size();  for(int i = 0; i < n; ++i) {    if(s_comment == true && str[i] == '\n') {      s_comment = false;    }    else if(m_comment == true && str[i] == '*' && str[i+1] == '/') {      m_comment = false; i++; }    else if(m_comment || s_comment) continue;    else if(str[i] == '/' && str[i + 1] == '/') {      s_comment = true;      i++; }    else if(str[i] == '/' && str[i+1] == '*') {      m_comment = true;      i++;}    else res += str[i];  }  return res;}


0 0