[英]Clean all spaces and newlines C or Lex/Bison
I need to clean all spaces and newlines (\\n) of the yytext on my Lex/Bison program. 我需要在Lex / Bison程序中清理yytext的所有空格和换行符(\\ n)。
I have a proprierty like this: 我有这样的倾向:
<PROPERTY>[^}]* TAG=yytext;
I need it to parse all my CSS code file into the HTML tags. 我需要它来将我所有的CSS代码文件解析为HTML标记。
I tried something like this: 我尝试过这样的事情:
sizeOfArray=strlen(TAG);
int i;
for(i=0; i<sizeOfArray; i++){
memmove(TAG,TAG+1,len);
}
Without success... 没有成功...
EDIT: 编辑:
I only want clean the spaces before the property and after it. 我只想清理属性之前和之后的空间。
example: 例:
body {
background: black;
color: #80c0c0
}
Because I want put this lines on my HTML file, to be something like this: 因为我想把这些行放在我的HTML文件中,所以像这样:
<body style="background:black; color:#80c0c0;">
Untested, but if isspace()
from <ctype.h>
matches the characters (blanks, tabs, newlines) that you want to skip, this should work: 未经测试,但是如果
<ctype.h>
中的isspace()
与您要跳过的字符(空白,制表符,换行符)匹配,则此方法应该起作用:
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (!isspace(TAG[i]))
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
As discussed in the comments, this code should implement 'for each sequence of one or more newlines or spaces, preserve a single space; 如评论中所讨论的,此代码应实现“对于一个或多个换行符或空格的每个序列,保留一个空格; copy other characters through unchanged', again assuming
isspace()
is a suitable function — there's also isblank()
, for example, in the Standard C library. 通过“保持不变复制其他字符”,再次假设
isspace()
是合适的函数-例如,在Standard C库中还有isblank()
。
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (isspace(TAG[i]))
{
while (i < sizeOfArray && isspace(TAG[i]))
i++;
if (TAG[i] != '\0')
TAG[j++] = ' ';
}
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
Now tested with this SSCCE ( Short, Self-Contained, Correct Example ): 现在使用此SSCCE( 简短,独立,正确的示例 )进行了测试:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
static void squish_whitespace(char *TAG)
{
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (isspace(TAG[i]))
{
while (i < sizeOfArray && isspace(TAG[i]))
i++;
if (TAG[i] != '\0')
TAG[j++] = ' ';
}
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
}
int main(void)
{
char data[][80] =
{
"abc def ghi",
"abc def \t\t\n\nghi",
"abc def ghi ",
"body {\n" // NB: string concatenation
" background: black;\n"
" color: #80c0c0\n"
" }"
};
enum { NUM_DATA = sizeof(data) / sizeof(data[0]) };
for (size_t i = 0; i < NUM_DATA; i++)
{
printf("Before: [[%s]]\n", data[i]);
squish_whitespace(data[i]);
printf("After: [[%s]]\n", data[i]);
}
return 0;
}
Output from test data: 测试数据输出:
Before: [[abc def ghi]]
After: [[abc def ghi]]
Before: [[abc def
ghi]]
After: [[abc def ghi]]
Before: [[abc def ghi ]]
After: [[abc def ghi]]
Before: [[body {
background: black;
color: #80c0c0
}]]
After: [[body { background: black; color: #80c0c0 }]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.