繁体   English   中英

清理所有空间和换行符C或Lex / Bison

[英]Clean all spaces and newlines C or Lex/Bison

我需要在Lex / Bison程序中清理yytext的所有空格和换行符(\\ n)。

我有这样的倾向:

<PROPERTY>[^}]* TAG=yytext;

我需要它来将我所有的CSS代码文件解析为HTML标记。

我尝试过这样的事情:

sizeOfArray=strlen(TAG);
int i;
for(i=0; i<sizeOfArray; i++){
    memmove(TAG,TAG+1,len);
}

没有成功...

编辑:

我只想清理属性之前和之后的空间。

例:

 body {
         background: black;
         color: #80c0c0
         }

因为我想把这些行放在我的HTML文件中,所以像这样:

<body style="background:black; color:#80c0c0;"> 

未经测试,但是如果<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';

如评论中所讨论的,此代码应实现“对于一个或多个换行符或空格的每个序列,保留一个空格; 通过“保持不变复制其他字符”,再次假设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';

现在使用此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;
}

测试数据输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM