Skip to content

Instantly share code, notes, and snippets.

@porimol
Last active August 7, 2017 15:44
Show Gist options
  • Save porimol/28ee01e55b00b56ec34cf7cc0cd82589 to your computer and use it in GitHub Desktop.
Save porimol/28ee01e55b00b56ec34cf7cc0cd82589 to your computer and use it in GitHub Desktop.
Lexical analyzer using c programming language
#include <stdio.h>
#include <string.h>
void lexicalAnalyzer(char S[]);
int isIdent(char ch);
int isAlpha(char ch);
int isDigit(char ch);
int isOperator(char ch);
int isDel(char ch);
void isKeyword();
char A[100], ident[50][30], oper[50][5], delim[50][5], keyword[180][20];
int i=0, j=0, c=0, k=0, idi=0, idj=0, opi=0, opj=0, deli=0, delj=0;
char op[8] = {'+', '-', '*', '/', '=', '&', '|', '!'};
char del[8] = {'(', ')', '{', '}', '[', ']', '"', ';'};
char kword[32][30] = {
"auto",
"double",
"int",
"struct",
"break",
"else",
"long",
"switch",
"case",
"enum",
"register",
"typedef",
"char",
"extern",
"return",
"union",
"const",
"float",
"short",
"unsigned",
"continue",
"for",
"signed",
"void",
"default",
"goto",
"sizeof",
"volatile",
"do",
"if",
"static",
"while"};
int main()
{
gets(A);
lexicalAnalyzer(A);
return 0;
}
void lexicalAnalyzer(char S[]){
i=0;
while(S[i]){
if(isIdent(S[i])){
while(isIdent(S[i])){
ident[idi][idj] = S[i];
idj++;
i++;
}
ident[idi][idj] = '\0';
idi++;
idj=0;
} else if(isOperator(S[i])){
while(isOperator(S[i])){
oper[opi][opj] = S[i];
opj++;
i++;
}
oper[opi][opj] = '\0';
opi++;
opj=0;
} else if(isDel(S[i])){
while(isDel(S[i])){
delim[deli][delj] = S[i];
delj++;
i++;
}
delim[deli][delj] = '\0';
deli++;
delj=0;
} else{
i++;
}
}
isKeyword();
printf("\nIdentifier\n-------------------\n");
for(i=0; i<=idi; i++)
printf("%s\n", ident[i]);
printf("Operator\n-------------------\n");
for(i=0; i<=opi; i++)
printf("%s\n", oper[i]);
printf("Delimiter\n-------------------\n");
for(i=0; i<=deli; i++)
printf("%s\n", delim[i]);
printf("Keywords\n-------------------\n");
for(i=0; i<=c; i++)
printf("%s\n", keyword[i]);
}
int isIdent(char ch){
if(isAlpha(ch) || isAlpha(ch) || isDigit(ch) || ch=='_'){
return 1;
} else{
return 0;
}
}
int isAlpha(char ch){
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
return 1;
} else{
return 0;
}
}
int isDigit(char ch){
if(ch >= '0' && ch <= '9'){
return 1;
} else{
return 0;
}
}
int isOperator(char ch){
for(k = 0; k < 8; k++)
if(ch == op[k])
return 1;
return 0;
}
int isDel(char ch){
for(k = 0; k < 8; k++)
if(ch == del[k])
return 1;
return 0;
}
void isKeyword(){
for(i = 0; i < idi; i++){
for(j = 0; j < 32; j++){
if(!strcmp(ident[i], kword[j])){
strcpy(keyword[c++], ident[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment