(1)识别该语言词法规则的状态转换图如下:
![词法分析器状态转换图](https://i.imgur.com/2Q9Xz5O.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 c) {
char* operators = "+-*/%=";
return strchr(operators, c) != NULL;
}
// 判断是否为界符
int isDelimiter(char c) {
char* delimiters = "(){}[],;";
return strchr(delimiters, c) != NULL;
}
// 识别单词
void recognizeToken(char* token) {
if (isKeyword(token)) {
printf("(%d, %s)\n", KEYWORD, token);
} else if (isdigit(token[0])) {
printf("(%d, %s)\n", CONSTANT, token);
} else if (isalpha(token[0])) {
printf("(%d, %s)\n", IDENTIFIER, token);
} else if (isOperator(token[0])) {
printf("(%d, %s)\n", OPERATOR, token);
} else if (isDelimiter(token[0])) {
printf("(%d, %s)\n", DELIMITER, token);
} else {
printf("(%d, %s)\n", ERROR, token);
}
}
int main() {
char input[100];