a. Create a Lexer to
take input from text file and count no of characters, no. of lines & no. of
words.
%{
#include<stdio.h>
int lines=0,
words=0,s_letters=0,c_letters=0, num=0, spl_char=0,total=0;
%}
%%
\n { lines++;
words++;}
[\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%
main(void)
{
yyin=
fopen("myfile.txt","r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This
File contains ...");
printf("\n\t%d
lines", lines);
printf("\n\t%dwords",words);
printf("\n\t%d
small letters", s_letters);
printf("\n\t%d
capital letters",c_letters);
printf("\n\t%d
digits", num);
printf("\n\t%d
special characters",spl_char);
printf("\n\tIn
total %d characters.\n",total); }
INPUT AND OUTPUT
Input
'myfile.txt' contains
this.
This is my 1st lex
program!!!
It is Fun
Output
This file contains..
2 lines
9 words
24 small letters
3 capital letters
1 digits
3 special characters
In total 42
characters.
b. Write a Lex program
to count number of vowels and consonants in a given input string.
%{ #include<stdio.h>
int vowels=0;
int cons=0;
%}
%%
[aeiouAEIOU]
{vowels++;}
[a-zA-Z]
{cons++;}
%%
main()
{
printf(“Enter the
string.. at end press ^d\n”);
yylex();
printf(“No of
vowels=%d\nNo of consonants=%d\n”, vowels,cons);
}
INPUT AND OUTPUT
Input : HI XYZ
Output : No of vowels
= 2
No of consonants = 3