不改变原始值的字符串连接 - C

String concatenation without altering original values - C

我正在通过使用 C 的字符串连接来发出动态 PUT 请求。我的问题是在第一次请求之后,我需要保持静态的字符串 putEndpoint 被字符​​串连接改变了我正在使用它。

char putEndpoint[] = "PUT /api/v1/products/";
char http[] = " HTTP/1.1";
char productID[idLen];

for(int i = 0; i < 13; i++) {
  productID[i] = newTag[i];
}

// going into this strcat, putEndpoint correctly = "PUT /api/v1/products/"

char *putRequestID = strcat(putEndpoint,productID);

// putEndpoint now = "PUT /api/v1/products/xxxxxxxxxxx"

char *putRequestEndpoint = strcat(putRequestID,http);

现在,如果我要进行第二次调用(我需要这样做),putEndpoint 会初始化为 "PUT /api/v1/products/xxxxxxxxxxx"

EDIT: Is there an alternative to strcat() that could accomplish this concatenation? I now understand that strcat() is meant to alter values.

您可以使用 sprintf.

A simple working example-

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

 int main(void) {

      char putEndpoint[] = "PUT /api/v1/products/";
      char http[] = " HTTP/1.1";
      char *putRequestEndpoint;

      putRequestEndpoint=malloc(strlen(putEndpoint)+strlen(http)+1); //allocating memory

      sprintf(putRequestEndpoint,"%s%s",putEndpoint,http); // formatted output is stored in putRequestEndpoint
      printf("%s\n",putRequestEndpoint);
      printf("%s",putEndpoint); // will print original string unchanged.
      free(putRequestEndpoint);  //freeing memory
      return 0;
   }

我最终将 putEndpoint 更改为常量并创建了一个缓冲区数组,然后将其复制 putEndpoint 到其中。该数组随后会在每次请求后重置。

const char putEndpoint[] = "PUT /api/v1/products/";
char http[] = " HTTP/1.1";
char productID[idLen];

char putRequestBuffer[100];
strcpy(putRequestBuffer, putEndpoint);
strcat(putRequestBuffer, productID);

char *putRequestEndpoint = strcat(putRequestBuffer,http);

memcpy 和具有固定大小和适当边界检查的静态数组是你的朋友,我的朋友。

您必须使用代码重置它。如果您将 putEndpoint[] 更改为常量,这将使您的第一行看起来像

const char putEndpoint[] = "PUT /api/v1/products/";

编译器会在您第一次 strcat(putEndpoint,...) 时给您一个错误,因为 strcat 将尝试写入常量变量。这将迫使您寻找替代解决方案。

下面的代码根据需要为端点字符串干净地分配临时内存,将第一个字符串复制到其中,将接下来的两个字符串连接到它上面,使用它,最后取消分配它并将指针设置回 NULL。

int lengthEndpoint = 0;
char* putRequestEndpoint = NULL;

lengthEndpoint = strlen(putEndpoint) + strlen(productID) + strlen(http);
lengthEndpoint += 1; // add room for null terminator

putRequestEndpoint = malloc(lengthEndpoint);
strcpy(putRequestEndpoint, putEndpoint);
strcat(putRequestEndpoint, productID);
strcat(putRequestEndpoint, http);

// do something with putRequestEndpoint

free(putRequestEndpoint);
putRequestEndpoint = NULL;

在回答这个问题之前,我用这个 WIKIBOOKS site 刷新了我对 C 字符串操作的记忆。我建议您进一步阅读此主题。