Tuesday 1 April 2014

15. Lex program to count number of spaces in the file

The question is self explanatory

Here is the code:

%{
    int i=0;
%}
%%
[ ] {printf(" ");i++;}
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
printf("\nTotal spaces = %d\n",i);
}

14. Lex program to remove every word that start with t

The question is self explanatory

Here is the code:


%{
%}
%%
t[a-z A-Z]+ printf("");
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
}

13.Lex program to print every words in parenthesis

 The program shows every words in file "new" in parenthesis.

For example

I am going
We are going

becomes

{I} {am} {going}
{We} {are} {going}

%{
   
%}
%%
[a-zA-Z]+ {printf("{%s}",yytext);}
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
}

12. Lex program to put every line in parenthesis

The program puts every line in parenthesis.
For example

I am going
We are going

appears

{I am going}
{We are going}

Here is the code :

%{
   
%}
%%
[a-z A-Z]+ {printf("{%s}",yytext);}
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
}

11. Lex program to remove all newline characters

It removes all new line characters and prints everything in a line.

For example

I am
Going

appears

I am Going

Here is the code:

%{
%}
%%
\n    printf("");
%%
main()
{
    extern FILE *yyin;
    yyin=fopen("new","r");
    yylex();
}

10.Lex program to print every lines in a file with its line number

Question is self explanatory

Here is the code:


%{
    int i=0;
%}
%%
[a-z A-Z]+ {printf("%d:%s",i,yytext);i++;}
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
}

9. Lex program to view file contents with double line spacing

It reads every line and prints it. It gives a line gap between every line.

for example
I am going
She is going

appears

I am going

She is going


%{
   
%}
%%
\n {printf("\n\n",yytext);}
%%

main()
{
extern FILE *yyin;
yyin=fopen("new","r");
yylex();
}