首页 > 解决方案 > 'for'块内的字符串“连接”

问题描述

我正在尝试在 C 中实现某种“连接”以在一个字符串中使用几个值。

代码如下所示:

#include <stdio.h>

#define A "A"

int main() {

    char *textArray[] = {"a", "b", "c"};
    int intArray[] = {1, 2, 3};

    int n;
    // count intArray[] lengh
    // example taken from the https://www.sanfoundry.com/c-program-number-elements-array/
    n = sizeof(intArray)/sizeof(int);

    int i;
    char *concat;
    for (i=0; i<n; i++) {
        // check if values are accessible
        printf("TEST: Macro: %s, textArray's value: %s, intArray's value: %d\n", A, textArray[i], intArray[i]);

        // making concatenation here - this will work
        concat = "Macro: " A " textArray's value: '' intArray's value: ''";

        // this will NOT work
        // expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
        // concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
        printf("%s\n", concat);
    }

    return 0;
}

此代码A仅在使用宏的值时工作正常:

$ ./array_test 
TEST: Macro: A, textArray's value: a, intArray's value: 1
Macro: A textArray's value: '' intArray's value: ''
TEST: Macro: A, textArray's value: b, intArray's value: 2
Macro: A textArray's value: '' intArray's value: ''
TEST: Macro: A, textArray's value: c, intArray's value: 3
Macro: A textArray's value: '' intArray's value: ''

但是,如果我尝试使用textArray[i],即:

...
// making concatenation here - this will work
// concat = "Macro: " A " textArray's value: '' intArray's value: ''";

// this will NOT work
// expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
printf("%s\n", concat);
...

我在编译时出错:

$ gcc array_test.c -o array_test
array_test.c: In function ‘main’:
array_test.c:26:53: error: expected ‘;’ before ‘textArray’
         concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];

所以问题是:我在这里做错了什么,实现目标的正确方法是什么?

UPD:最终目标是将一个字符串传递给类似的函数mysql_query(),例如mysql_query(conn, concat)其中concat将包含类似的值"INSERT INTO TableName VALUES('textValue', 'intValue')"

标签: carraysstringconcatenation

解决方案


"string" "string1" "string2"不是串联。它只是字符串文字的语法正确形式之一。


推荐阅读