Lex程序可计算行,空格和制表符的数量

2021年5月1日17:17:56 发表评论 807 次浏览

Lex是一种生成词法分析器的计算机程序, 由Mike Lesk和Eric Schmidt编写。 Lex读取指定词法分析器的输入流, 并输出以C编程语言实现词法分析器的源代码。

让我们看看如何使用Lex计算行数, 空格和制表符的数量。

例子:

Input:
Geeks for       Geeks 
gfg  gfg

Output:
No. of lines=2 
No. of spaces=3 
No. of tabs=1 
No. of other characters=19

Input:
Hello
How    are    you?

Output:
No. of lines=2 
No. of spaces=4 
No. of tabs=1 
No. of other characters=15

下面是实现:

/*lex code to count the number of lines, tabs and spaces used in the input*/
  
%{
#include<stdio.h>
int lc=0, sc=0, tc=0, ch=0; /*Global variables*/
%}
  
/*Rule Section*/
%%
\n lc++; //line counter
([ ])+ sc++; //space counter
\t tc++; //tab counter
. ch++;     //characters counter
%%
  
main()
{
     //The function that starts the analysis
     yylex();
      
     printf ("\nNo. of lines=%d, lc);  
     printf ("\nNo. of spaces=%d, sc);
     printf ("\nNo. of tabs=%d, tc);
     printf ("\nNo. of other characters=%d, ch);
      
}

输出如下:

Lex程序可计算行,空格和制表符的数量1

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: