Skip to content
Related Articles
Open in App
Not now

Related Articles

Lex program to count the number of lines, spaces and tabs

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 12 Jan, 2023
Improve Article
Save Article
Like Article

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




/* DESCRIPTION/DEFINITION SECTION */
%{
#include<stdio.h>
int lc=0,sc=0,tc=0,ch=0,wc=0;        // GLOBAL VARIABLES
%}
 
// RULE SECTION
%%
[\n] { lc++; ch+=yyleng;}
[  \t] { sc++; ch+=yyleng;}
[^\t] { tc++; ch+=yyleng;}
[^\t\n ]+ { wc++;  ch+=yyleng;} 
%%
 
int yywrap(){ return 1;    }
/*        After inputting press ctrl+d         */
 
// MAIN FUNCTION
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: 
 

 

 

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!