实现删除嵌套的注释

实现删除嵌套的注释。每次从键盘上读取三行字符串。若发现存在嵌套的情况,即在注释内又存在的/*或*/,就把这/*或*/删除,注释外的部分保留。/与*优先级是左结合,即当前出现/*/时,优先删除/*。

 

例如:

输入:

/*1234*/

abc/****//****/def

123/**/*****/*******/xxx

输出:

/*1234*/

abc/****//****/def

123/************/xxx

 

输入:

/*****/***//****/

adb/*****//*/897

efg/*****//

输出:

/*********/

adb/****/897

efg/****/

我的实现如下:

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <iterator>

using namespace std;


int delete_nested_comment(string &strInput)
{
	int i = 0;
	string strTemp;
	int nIndex = strInput.length();
	stack<char> staReverse;
	stack<char> staForward;
	
	/* 当入栈完成后,栈里面只剩下一个斜杠 */
	while (nIndex > i)
	{
		switch (strInput[i])
		{
			case '/':
			{
				/* 压入第一个斜杠 */
				if ((staReverse.empty()) || ('*' != staReverse.top()))
				{
					staReverse.push(strInput[i]);
					i++;
				}
				/* 其它的斜杠全部删除 */
				else
				{
					i++;
				}
				
				break;
			}
			case '*':
			{
				staReverse.push(strInput[i]);
				i++;

				break;
			}

			default:
			{
				staReverse.push(strInput[i]);
				i++;

				break;
			}
		}
	}

	/* 出栈,补上入栈时缺少的一个斜杠 */
	if ('*' == staReverse.top())
	{
		staReverse.push('/');
		while (!staReverse.empty())
		{
			staForward.push(staReverse.top());
			staReverse.pop();
		}
	}
	else
	{
		while (!staReverse.empty())
		{
			if ('*' != staReverse.top())
			{
				staForward.push(staReverse.top());
				staReverse.pop();
			}

			if (('*' == staReverse.top()) && ('*' != staForward.top()))
			{
				static int nInsertFlg = 0;  //由于只缺少一个斜杠,所以只插入一次
				if (0 == nInsertFlg)
				{
					staForward.push('/');
					nInsertFlg = 1;
				}
				
				staForward.push(staReverse.top());
				staReverse.pop();
			}
			//if ('*' == staReverse.top())
			else
			{
				staForward.push(staReverse.top());
				staReverse.pop();
			}
		}
	}

	while (!staForward.empty())
	{
		strTemp += staForward.top();
		staForward.pop();
	}

	strInput = strTemp;

	return 0;
}

int main(void)
{
	string strTemp;
	vector<string> vecInput;

	cout << "Please input your string, Q/q stop!" << endl;
	cin >> strTemp;
	while (("q" != strTemp))
	{
		vecInput.push_back(strTemp);
		cin >> strTemp;
	}
	
	vector<string>::iterator iter = vecInput.begin();
	cout << "Output result is:" << endl;
	for (iter = vecInput.begin(); iter != vecInput.end(); iter++)
	{
		delete_nested_comment(*iter);
		cout << (*iter) << endl;
	}
		
	
	return 0;
}

执行结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值