2012华为编程大赛第三题

// Analysis.cpp : 定义控制台应用程序的入口点。
//

/*
2012华为编程大赛第三题
3. 语法分析(40分)
问题描述: 
编译器通过语法分析来检测程序的一些语法问题。要求实现一个简单的语法分析程序,判断输入的字符串是否有符合要求的语法组合。
需要判断的语法组合有:
if  then
if  ( )  then
switch case end
switch ( ) case end
switch ( ) case default end
do while
要求实现函数: 
void analysis(char *str,int *num)
【输入】  char *str,待分析字符串      
【输出】  int num,匹配的组合个数
【返回】  无
注:输入字符串中关键字以空格隔开,"if"、"("、")"、"case"等均表示关键字,从左向右,找到匹配的组合即可,组合一定是相互分离,不会嵌套,不会有交叉情况出现。
示例 
输入:str = if then,
输出:num = 1

输入:str = switch case aaa ,
输出:num = 0

输入:str = if ( aaa ) then do bbb while switch cas ,
输出:num = 2


// 解者注:注意到题目中提到没有嵌套,解题思路来自网上看的别人的解法。
*/


#include "stdafx.h"
#include "iostream"
#include "sstream"



using namespace std;

string mstr[6] = {"if then","if ( ) then","switch case end","switch ( ) case end","switch ( ) case default end","do while"};
string keystr[10] = {"if","then","(",")","switch","case","end","default","do","while"};
bool iskey(string &str)
{

	for(int i=0;i<10;++i)
		if(str == keystr[i])
			return true;
	return false;
}

bool ismatch(string &str)
{

	for(int i=0;i<6;++i)
		if(str == mstr[i])
			return true;
	return false;
}

void analysis(char *str,int *num)
{
	istringstream stream((string)(str));
	string word;
	string smatch("");
	//vector<string> vstr;
	int i=0;
	*num = 0;
	while(stream>>word)
	{
		if(iskey(word))
		{
			if(smatch.empty())
				smatch.append(word);
			else if (word == "if" || word == "switch" || word == "do")
			{
				smatch.erase();
				smatch.append(word);
			}
			else
			{
				smatch.append(" ");
				smatch.append(word);

			}

		}
		if(ismatch(smatch))
		{
			(*num)++;

			smatch.erase();
		}

	}

}


int _tmain(int argc, _TCHAR* argv[])
{
	char str[500];
	memset (str, 0, 500);
	int num;
	cout << "输入语句:";
	cin.getline(str, 500);
	analysis(str, &num);
	cout << "匹配的组合个数为" << num << endl;
	system("pause");
	return 0;
}
好吧,这就基本上全是别人的代码了,上个链接就好 http://www.cnblogs.com/ballwql/archive/2013/04/18/3028709.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值