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
下面是实现:
C
/*lex code to count the number of lines,
tabs and spaces used in the input*/
%{
#include
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
%%
int 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);
}
输出:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。