5. Write a lex program to find out the total number of vowels and consonants from the given input string.
Sure, I can provide you with a Lex program that counts the total number of vowels and consonants in a given input string. I'll also explain each line of code for better understanding.
```lex
%{
#include <stdio.h>
int vowelCount = 0;
int consonantCount = 0;
%}
%%
[aAeEiIoOuU] { vowelCount++; }
[^aAeEiIoOuU\n]+ { consonantCount++; }
\n { /* Ignore newline characters */ }
. { /* Ignore other characters */ }
%%
int main() {
yylex();
printf("Total Vowels: %d\nTotal Consonants: %d\n", vowelCount, consonantCount);
return 0;
}
```
Explanation of each line of code:
1. `%{` and `%}`: These are used to enclose C code that is to be included at the beginning of the generated C code.
2. `#include <stdio.h>`: This includes the standard input/output library for using functions like `printf`.
3. `int vowelCount = 0;` and `int consonantCount = 0;`: These declare integer variables to keep track of the counts of vowels and consonants.
4. `%%`: This separates the Lex specifications from the C code.
5. `[aAeEiIoOuU] { vowelCount++; }`: This rule matches any vowel (both lowercase and uppercase) and increments the `vowelCount`.
6. `[^aAeEiIoOuU\n]+ { consonantCount++; }`: This rule matches any non-vowel character (including consonants and other characters), except newline characters, and increments the `consonantCount`.
7. `\n { /* Ignore newline characters */ }`: This rule ignores newline characters.
8. `.{ /* Ignore other characters */ }`: This rule ignores any other characters that do not match the previous rules.
9. `%%`: This separates the Lex rules from the C code that follows.
10. `int main() { yylex(); ... }`: This is the `main` function that calls `yylex()` to start the Lex scanner. After the scanning is complete, it prints the total number of vowels and consonants.
The Lex program processes the input character by character and matches against the specified rules. If a vowel is found, the `vowelCount` is incremented; if a consonant is found, the `consonantCount` is incremented. Finally, the program prints the counts of vowels and consonants in the input string.
Remember that this is a simple example. It might not handle all edge cases perfectly, and optimizations can be made.
Comments
Post a Comment