(1) 识别该语言词法规则的状态转换图如下:
![词法分析器状态转换图](https://i.imgur.com/8L4JF5t.png)
(2) 根据状态转换图,可以设计并编写以下词法分析程序:
```c
#include
#include
#include
#define MAX_TOKEN_LEN 100
// 定义种别码
enum TokenType {
KEYWORD,
IDENTIFIER,
CONSTANT,
OPERATOR,
DELIMITER,
ERROR
};
// 判断是否为关键字
int isKeyword(char* token) {
char* keywords[] = {"if", "else", "while", "do", "for", "int", "float", "char", "return"};
int numKeywords = sizeof(keywords) / sizeof(keywords[0]);
for (int i = 0; i < numKeywords; i++) {
if (strcmp(token, keywords[i]) == 0) {
return 1;
}
}
return 0;
}
// 判断是否为运算符
int isOperator(char ch) {
char operators[] = "+-*/%=";
int numOperators = strlen(operators);
for (int i = 0; i < numOperators; i++) {
if (ch == operators[i]) {
return 1;
}
}
return 0;
}
// 判断是否为界符
int isDelimiter(char ch) {
char delimiters[] = "(){}[],;";
int numDelimiters = strlen(delimiters);
for (int i = 0; i < numDelimiters; i++) {
if (ch == delimiters[i]) {
return 1;
}
}
return 0;
}
// 输出单词的种别码和值
void printToken(int type, char* token) {
switch (type) {
case KEYWORD:
printf("关键字\t%s\n", token);
break;
case IDENTIFIER:
printf("标识符\t%s\n", token);
break;
case CONSTANT:
printf("常数\t%s\n", token);
break;
case OPERATOR:
printf("运算符\t%c