gpt4 book ai didi

c - 如何在另一个字符串的中间添加一个字符串变量?

转载 作者:行者123 更新时间:2023-11-30 21:15:19 24 4
gpt4 key购买 nike

我有一个c程序如下:

char* data1 = "test";//Here i have given some dummy value, the value will be evaluated in runtime
char* variable1 = "<Method name=\"data1\">";

我使用这段代码面临的问题是,而不是 data1的值data1它自身存储的变量名称为 variable1 。所以我想知道这里变量 data1 的位置(如第 2 行所示),我如何获得 test 这是它在执行过程中的值。

variable1 的预期结果:<Method name="test">

我期望的实际结果为variable1 :<Method name="data1">

在java中我使用“+”运算符,我正在努力在C中实现。

最佳答案

您可以使用 sprintfsnprintf 函数和 %s 占位符,如下所示:

#include <stdio.h>

int main (void)
{
char* data1 = "test";//Here i have given some dummy value, the value will be evaluated in runtime
char* variable1 = "<Method name=\"%s\">";

char result[500];

sprintf(result, variable1, data1);

snprintf(result, 500, variable1, data1);

return 0;
}

关于c - 如何在另一个字符串的中间添加一个字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com