词法分析

Posted 115叶霆毅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了词法分析相关的知识,希望对你有一定的参考价值。

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

int panduan(char tmp[])
{
char b[6][10] = {"begin", "if", "then", "while", "do", "end", };
int k = 0;

while(k < 6) // 临时变量tmp 与 字符串b[k] 进行比较
{
if(strcmp(tmp, b[k]) == 0)
{
printf("<%s, %d>\n", tmp, k+1);
return 0;
}
k++;
}
printf("<%s, 10>\n", tmp);

return 0;
}

void cifafenxi(char a[])
{
int i = 0, j = 0;
char tmp[10];
int flag = 0;

while(a[i] != ‘\0‘)
{
if(a[i] >= ‘a‘ && a[i] <= ‘z‘) // 判断标识符
{
tmp[j] = a[i];
j++;
while((a[i+1] >= ‘a‘ && a[i+1] <= ‘z‘) || (a[i+1] >= ‘0‘ && a[i+1] <= ‘9‘))
{
i++;
tmp[j] = a[i];
j++;
}
tmp[j] = ‘\0‘;
j = panduan(tmp);
}

if(a[i] >= ‘0‘ && a[i] <= ‘9‘) // 判断数字
{
tmp[j] = a[i];
j++;
while(a[i+1] >= ‘0‘ && a[i+1] <= ‘9‘)
{
i++;
tmp[j] = a[i];
j++;
}
tmp[j] = ‘\0‘;
printf("<%s, 11>\n", tmp);
j = 0;
}

switch(a[i]) // 判断符号
{
case ‘+‘:printf("<+, 13>\n");break;
case ‘-‘:printf("<-, 14>\n");break;
case ‘*‘:printf("<*, 15>\n");break;
case ‘/‘:printf("</, 16>\n");break;
case ‘:‘:
{
if(a[i+1] == ‘=‘)
printf("<:=, 18>\n");
else
printf("<:, 17>\n");
}break;
case ‘<‘:
{
if(a[i+1] == ‘=‘)
printf("<<=, 21>\n");
else if(a[i+1] == ‘>‘)
printf("<<>, 22>\n");
else
printf("<<, 20>\n");
}break;
case ‘>‘:
{
if(a[i+1] == ‘=‘)
printf("<>=, 24>\n");
else
printf("<>, 23>\n");
}break;
case ‘=‘:printf("<=, 25>\n");break;
case ‘;‘:printf("<;, 26>\n");break;
case ‘(‘:printf("<(, 27>\n");break;
case ‘)‘:printf("<), 28>\n");break;
case ‘#‘:printf("<#, 0>\n");break;
}

i++;
}
}

int main(void)
{
char a[300];

printf("input : ");
gets(a);
cifafenxi(a);

return 0;
}

以上是关于词法分析的主要内容,如果未能解决你的问题,请参考以下文章

编译原理词法分析

三词法分析

Second-词法分析

词法分析

词法分析器

词法分析