防止字符串输出中出现空格

时间:2019-02-07 15:08:45

标签: c c-preprocessor

我有一个C预处理程序宏

#define QUOTE(...) #__VA_ARGS__

如果我使用它来像这样将JSON字符串化:

QUOTE(
{
    "a":1,
    "b":2
}
)

输出为

"{ \"a\":1, \"b\":2 }"

有什么方法可以删除空格?即

"{\"a\":1,\"b\":2}"

如果没有,更广泛的问题是我正在编写用于JSON解析的测试用例,并且我想使JSON在测试用例中可读,但在没有空格的情况下进行压缩。测试完解析后,我测试了从解析结果生成JSON输出,并想与原始字符串进行比较,但是生成的JSON不包含空格。也许还有其他解决方案,而不是使用宏...

1 个答案:

答案 0 :(得分:1)

由于我的JSON值不包含空格,所以到目前为止,我最好的解决方案是在创建字符串后删除空格:

#define QUOTE(...) #__VA_ARGS__

size_t stripSpaces(char *orig, size_t length) {
    for (size_t i = 0; i < length; i++) {
        if(orig[i] != ' ') { continue; }
        memmove(&orig[i], &orig[i+1], length - i - 2);
        i--;
        length--;
    }
    return length;
}

void unitTest() {
    char json[] = QUOTE(
        {
            "messageType":176,
            "channel":1,
            "controller":67,
            "ccValue":127
        }
    );

    size_t jsonLength = stripSpaces(json, sizeof(json));
}

编辑:由于@Bodo的建议,我不但不删除空格,而且在比较字符串时也可以忽略空格。

bool compareJSON(const char * string1, size_t string1Size, const char * string2, size_t string2Size) {
    bool inQuotes = false;
    for (size_t string1Pos = 0, string2Pos = 0; string1Pos < string1Size && string2Pos < string2Size; ++string1Pos, ++string2Pos) {
        if(!inQuotes) {
            // skip spaces
            while(string1[string1Pos] == ' ' && string1Pos < string1Size) { string1Pos++; }
            while(string2[string2Pos] == ' ' && string2Pos < string2Size) { string2Pos++; }
            // check if we have reached the end of either
            if(string1Pos == string1Size || string2Pos == string2Size) {
                // if both at the end, equal strings, otherwise not equal
                return string1Pos == string1Size && string2Pos == string2Size;
            }
        }
        // compare character
        if(string1[string1Pos] != string2[string2Pos]) {
            return false;
        }
        if(string1[string1Pos] == '\"') {
            inQuotes = !inQuotes;
        }
    }
    return true;
}