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

Lex是一种生成词法分析器的计算机程序, 由Mike Lesk和Eric Schmidt编写。 Lex读取指定词法分析器的输入流, 并输出以C编程语言实现词法分析器的源代码。
让我们看看如何使用Lex计算行数, 空格和制表符的数量。
例子:

Input: Geeks forGeeks gfggfgOutput: No. of lines=2 No. of spaces=3 No. of tabs=1 No. of other characters=19Input: Hello Howareyou?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程序可计算行,空格和制表符的数量】输出如下:
Lex程序可计算行,空格和制表符的数量

文章图片

    推荐阅读