輸入一行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;}
輸出