您的位置:首页 > 其它

北航研究生复试2012上机第三题:统计关键字出现的位置

2018-02-23 18:15 337 查看
输入一行C语言代码,查找关键字if,while,for并按照出现顺序输出。输出格式:

关键字:位置

关键字:位置

还是字符串匹配的问题,为了方便,程序中本人写成从文件中读取主串,可以按照题目要求,改成控制台输入。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXSIZE 100

const char* fileName = "buaa123.in";
const char* keyword1 = "if";
const char* keyword2 = "while";
const char* keyword3 = "for";

typedef struct KeyWord{     //关键字节点 包括索引index和关键字字符串keyword[]
int index;
char keyword[6];
};

char* ReadFile(const char* fileName, int &len);     //从文件中读取主串
void BF(char* mstr,const char* sstr, KeyWord* arr, int &size);      //字符串匹配
bool Judge(char a, char b);                         //判断是关键字还是变量
void Sort(KeyWord* arr, int size);                  //关键字节点排序

int main(){

int len = 0;
char* str = ReadFile(fileName, len);//从文件中读取主串

KeyWord arr[MAXSIZE];
int size = 0;

BF(str,keyword1,arr,size);      //匹配关键字1
BF(str,keyword2,arr,size);      //匹配关键字2
BF(str,keyword3,arr,size);      //匹配关键字3

Sort(arr,size);                 //排序

for(int i = 0; i < size; i++){  //输出
printf("%s:%d\n",arr[i].keyword,arr[i].index);
}

return 0;
}

char* ReadFile(const char* fileName, int &len){
FILE* fp;
fp = fopen(fileName,"r");
if(fp == NULL){
printf("文件%s不能读入\n", fileName);
exit(1);
}
int ch;
while((ch = fgetc(fp)) != EOF){     //len记录文件大小
len++;
}

rewind(fp);

char* str = (char* )malloc(sizeof(char) * len + 1);
str[len] = '\0';
int i = 0;
while((ch = fgetc(fp)) != EOF){
str[i++] = ch;
}

fclose(fp);
return str;
}

void BF(char* mstr,const char* sstr, KeyWord* arr, int &size){
int len1 = strlen(mstr);
int len2 = strlen(sstr);
int i,j;
j = 0;
for(i = 0; i < len1; ){
if(mstr[i] != sstr[j]){     //不匹配
i = i - j + 1;
j = 0;
}else{                      //匹配
i++;
j++;
}
if(j >= len2){
if(Judge(mstr[i - j - 1],mstr[i])){ //是关键字
arr[size].index = i - len2 + 1;
strcpy(arr[size].keyword,sstr);
arr[size].keyword[len2] = '\0';
++size;
}
j = 0;
}
}
}

bool Judge(char a, char b){
if(a == ';' && b == '(')
return true;
if(a == ' ' && b == '(')
return true;
if(a == '{' && b == '(')
return true;
if(a == '}' && b == '(')
return true;
return false;
}

void Sort(KeyWord* arr, int size){      //冒泡排序
KeyWord temp;
int i,j;
for(i = 0; i <size; i++){
for(j = i+1; j < size; j++){
if(arr[j].index < arr[i].index){
temp.index = arr[i].index;
strcpy(temp.keyword,arr[i].keyword);

arr[i].index = arr[j].index;
strcpy(arr[i].keyword,arr[j].keyword);

arr[j].index = temp.index;
strcpy(arr[j].keyword,temp.keyword);
}
}
}
}


输入:

#include<stdio.h> int main() {int ifwhile=0; int forif=1; char if_for_while='a'; char *str="while";while(ifwhile==0){ifwhile=1;forif=0;}if(forif==0){if_for_while='b';}if(ifwhile==1){if_for_while='c';}return0;}


输出

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  机试