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:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Jan, 2023
Like Article
Save Article