//代码很不完善 比如若果if, while , for前面有空格也不会判断为关键字,输入时必须前面不能有空格,因为int if=0中if不是关键字,所以有缺陷...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#define MAXSIZE 300
#define WORDSIZE 20
struct node
{
char str[WORDSIZE];
int pos;
}word[MAXSIZE];
bool IsWord(char c)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
return true;
return false;
}
void Search(node word[MAXSIZE],int len)
{
int i;
for(i=0;i<len;i++)
{
// char str1="if";
// char str2="while";
// char str3="for";
if(strcmp(word[i].str,"if")==0||strcmp(word[i].str,"while")==0||strcmp(word[i].str,"for")==0)
printf("%s:%d\n",word[i].str,word[i].pos);
}
}
void Print(node word[MAXSIZE],int len)
{
}
int main()
{
/* int len =0; //按ctrl+z结束的写法
char ch;
while((ch=getchar())!=EOF)
{
str[len++]=ch;
}
char word[MAXSIZE][WORDSIZE]={'\0'};//初始化记录单词的数组 全为空*/
char str[MAXSIZE]={'\0'};//初始化 全为空
gets(str);
int len=strlen(str);
int i=0,j=0,k=0;
// int mark=0;//标记是不是单词的开始第一个字母 0是 1不是
for(k=0;k<len;k++)
{
if(str[k]=='i'&&str[k+1]=='f')
{
if(str[k-1]!='"'&&str[k-1]!='('&&str[k-1]!=' '&&str[k-1]!='_'&&str[k+2]!='_'&&!IsWord(str[k+2])&&!IsWord(str[k-1]))
{
strcpy(word[i].str,"if");
word[i].pos=k+1;//记录单词位置
i++;
// printf("abcabc if %s\n",word[i].str);
// printf("i=%d\n",i);
}
}
if(str[k]=='f'&&str[k+1]=='o'&&str[k+2]=='r')
{
if(str[k-1]!='('&&str[k-1]!=' '&&str[k-1]!='_'&&str[k+3]!='_'&&!IsWord(str[k+3])&&!IsWord(str[k-1]))
{
strcpy(word[i].str,"for");
word[i].pos=k+1;//记录单词位置
i++;
// printf("qweqwe for %s\n",word[i].str);
// printf("i=%d\n",i);
}
}
if(str[k]=='w'&&str[k+1]=='h'&&str[k+2]=='i'&&str[k+3]=='l'&&str[k+4]=='e')
{
if(str[k-1]!='('&&str[k-1]!=' '&&str[k-1]!='_'&&str[k+5]!='_'&&!IsWord(str[k+5])&&!IsWord(str[k-1]))
{
strcpy(word[i].str,"while");
word[i].pos=k+1;//记录单词位置
i++;
// printf("zxczxc while %s\n",word[i].str);
// printf("i=%d\n",i);
}
}
/* if(IsWord(str[k])&&str[k-1]!='"'&&str[k-1]!='_')
{
word[i].str[j++]=str[k];
if(mark==0)
word[i].pos=k+1;//记录单词位置
mark=1;
}
else
{
if(strcmp(word[i].str,"int"||strcmp(word[i].str,"char"||strcmp(word[i].str,"float")==0)
{
}
word[i].str[j]='\0';
i++;
j=0;
}*/
}
// printf("i=%d\n",i);
Search(word,i);
return 0;
}