#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool isKeyword(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
switch (state)
{
case 1:
if (str[left] == 'i')
{
state = 2;
break;
}
case 2:
if (str[left] == 'f')
{
state = 3;
break;
}
case 3:
if (str[left] == ' ')
{
state = 4;
break;
}
case 4:
printf("%s", "Token issued is <if>\n");
return true;
}
left += 1;
}
return (false);
};
bool isIdentifier(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
switch (state)
{
case 1:
if (str[left] == 'x')
{
state = 2;
break;
}
case 2:
if (!isalnum(str[left]))
{
state = 3;
break;
}
case 3:
printf("%s", "Token issued is <id, x>\n");
return true;
}
left += 1;
}
return false;
}
bool isNumber(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
char *token = "";
switch (state)
{
case 1:
if (
str[left] == '3')
{
token += '3';
state = 2;
break;
}
case 2:
if (str[left] == '0')
{
token += '0';
state = 2;
break;
}
else
{
state = 3;
break;
}
case 3:
printf("Token issued is <%s>\n", token);
return true;
}
left += 1;
}
return (false);
}
bool isRelOp(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
switch (state)
{
case 1:
if (str[left] == '>')
{
state = 2;
break;
}
case 2:
printf("%s", "Token issued is <RELOP, GT>\n");
return true;
}
left += 1;
}
return false;
}
bool isParentheses(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
switch (state)
{
case 1:
if (str[left] == '(')
{
state = 2;
break;
}
else if (str[left] == ')')
{
state = 3;
break;
}
case 2:
printf("%s", "Token issued is <PAREN, OPEN>\n");
return true;
case 3:
printf("%s", "Token issued is <PAREN, close>\n");
return true;
}
left += 1;
}
return false;
}
bool isWhiteSpace(char *str, int left, int right)
{
int state = 1;
while (left <= right)
{
switch (state)
{
case 1:
if (str[left] == ' ')
{
state = 2;
break;
}
case 2:
printf("%s", "Whitespace token not issued <>\n");
return true;
}
left += 1;
}
return false;
}
int main()
{
/* code */
char str[20];
printf("Enter input : ");
gets(str);
// printf("All Tokens are : \n");
printf("%s\n", str);
int left = 0, right = 0;
int len = strlen(str);
// printf("%d",len);
while (right <= len && left <= right)
{
// printf("%s", str);
// printf("%d", left);
// printf("%d", right);
if (isKeyword(str, left, right))
{
// left forward retract
left = right;
right -= 1;
}
else if (isIdentifier(str, left, right))
{
left = right;
right -= 1;
}
else if (isNumber(str, left, right))
{
left = right;
right -= 1;
}
else if (isRelOp(str, left, right))
{
left = right;
right -= 1;
}
else if (isParentheses(str, left, right))
{
left = right;
right -= 1;
}
else if (isWhiteSpace(str, left, right))
{
left = right;
right -= 1;
}
else
{
left = right;
right -= 1;
}
right += 1;
}
return 0;
}