Search code examples
cflex-lexerlexlexical-analysis

Lex program to count number of strings having ‘a’ as the second character


I wrote a program to count the number of strings having 'a' as the second character of the string. I tried using several patterns of the lex operators and also tried using the lex program start condition but none of them worked. This is the program that I wrote:

%{
  #include<stdio.h>
  #include<string.h>
  int count=0;
%}
%%
(^[a-z])/(a) {count++;}
%%
int yywrap(void){}
int main()
{   
  yylex();
  printf("\n%d strings with 'a' as second letter",count);
  return 0;
}

Solution

  • That's not a program to count all the strings that have an 'a' as the second character. For that you should change

    (^[a-z])/(a) {count++;}
    

    into

    ^.a          {count++;}
    

    (i should have also admitted an uppercase 'A', if you are interested in, but who knows with this specs you post)

    As you have written the regexp, it is a program to count the number of lines that start with an alphabetic letter and are continued with an 'a' character (the post context operator / has not too much to say here, as the second 'a' character will be read again, with no result, as the rest of the lexer doesn't take that fact in account. The only thing is that you will get only the first character of the line into the variable yytext. But you don't use yytext for anything...

    Probably, if you post what you are trying to do (the overall picture) more help can be given to you, but as you don't...