Reputation: 1981
I want to eliminate double quotes which are at the beginning and end of a string.
I take a string literal from my input file using a Lex rule as follows:
\".*\" {yyno++; yylval.string = strdup(yytext); return STRINGLITERAL;}
But when I use a string somewhere in Yacc program, I want to use only the string part.
Could you help me with this?
Upvotes: 0
Views: 3716
Reputation: 11
\".*\" {
yylval.string = (char*)calloc(strlen(yytext)-1, sizeof(char));
strncpy(yylval.string, &yytext[1], strlen(yytext)-2);
return STRINGLITERAL;
}
Jan explained it well, I'm just clarifying the lex and fixing a few typos for the next poor soul.
Upvotes: 1
Reputation: 133669
You just need to take the relevant part, eg:
// you allocate a string which is the length of the token - 2 " + 1 for '\0'
yylval.string = calloc(strlen(yytext)-1, sizeof(char));
// you copy the string
strncpy(yylval.string, &yytext[1], strlen(yytext-2));
// you set the NULL terminating at the end
yylval.string[yytext-1] = '\0';
So that if yytext == "\"foobar\""
first you allocate a string of length 8 - 2 + 1 = 7
bytes (which is correct since it will be foobar\0
, then you copy 8 - 2 characters starting from 'f'
, finally you set the NULL
terminating character.
Actually with calloc memory is already set to 0 so you don't need to place the NULL
terminating character but with malloc
you would.
Upvotes: 2