繁体   English   中英

字符串串联而不更改原始值-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"

编辑:有没有替代strcat()可以完成此串联? 我现在知道strcat()是用来更改值的。

您可以使用sprintf

一个简单的工作示例 -

#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,这将使您的第一行看起来像

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

第一次使用strcat(putEndpoint,...)时,编译器会给您一个错误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网站刷新了对C字符串操作的记忆。 我建议您进一步阅读该主题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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