Lex program to count the number of lines, spaces and tabs
Last Updated :
12 Jan, 2023
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Let’s the how to count the number of lines, spaces and tabs using Lex.
Example:
Input:
Geeks for Geeks
gfg gfg
Output:
Number of lines : 2
Number of spaces : 11
Number of tabs, words, charc : 0 , 5 , 32
Input:
Hello
How are you?
Output:
Number of lines : 2
Number of spaces : 8
Number of tabs, words, charc : 0 , 4 , 25
Below is the implementation:
C
%{
#include<stdio.h>
int lc=0,sc=0,tc=0,ch=0,wc=0;
%}
%%
[\n] { lc++; ch+=yyleng;}
[ \t] { sc++; ch+=yyleng;}
[^\t] { tc++; ch+=yyleng;}
[^\t\n ]+ { wc++; ch+=yyleng;}
%%
int yywrap(){ return 1; }
int main(){
printf ( "Enter the Sentence : " );
yylex();
printf ( "Number of lines : %d\n" ,lc);
printf ( "Number of spaces : %d\n" ,sc);
printf ( "Number of tabs, words, charc : %d , %d , %d\n" ,tc,wc,ch);
return 0;
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...