我想消除字符串开头和结尾的双引号。
我使用 Lex 规则从我的输入文件中获取一个字符串文字,如下所示:
\".*\" {yyno++; yylval.string = strdup(yytext); return STRINGLITERAL;}
但是当我在 Yacc 程序的某处使用字符串时,我只想使用字符串部分。
你能帮我吗?
最佳答案
你只需要做相关的部分,例如:
// 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';
因此,如果 yytext == "\"foobar\""
首先分配一个长度为 8 - 2 + 1 = 7
字节的字符串(这是正确的,因为它将是 foobar\0
,然后从 'f'
开始复制 8 - 2 个字符,最后设置 NULL
终止符。
实际上 calloc 内存已经设置为 0,因此您不需要放置 NULL
终止字符,但是使用 malloc
就可以了。
关于c - lex - 如何从字符串文字中消除双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14185172/