gpt4 book ai didi

c++ - 在 C 中修改一个 char* 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:07 24 4
gpt4 key购买 nike

我有这个:

char* original = "html content";

并想插入一个新的

char* mycontent = "newhtmlinsert";

</body>之前进入上面的“原始”在“原始”标签中。

我的新原件现在是:

char* neworiginal = "html content before </body>" + "newhtmlinsert" + "html content after </body>";

基本上我想获取一个 char* original 并将其转换为一个 char* neworiginal,它具有原始内容加上我在 </body> 之前添加的新内容在“原始html内容”中

这是修改后的代码,我还需要一些帮助:

* original data */
data = _msg_ptr->buff();
data_len = _msg_ptr->dataLen();


/*location of </body> in the original */

char *insert = strstr(data, "</body>");

/*length of the new buffer string */

int length = strlen(data)+strlen(ad_content);
newdata =(char*)malloc(sizeof(char)*length);
memset(newdata, 0, length);

/*copy the original data upto </body> into newdata*/

memcpy(newdata,data,insert-data);

/*now add the ad_content */
strcat(newdata,ad_content);

/*copy the data from </body> to end of original string(data) into newdata */

memcpy(newdata,data,data_len - ending );

我如何实现最后一条语句:memcpy(newdata,data,data_len - ending );

  i  need to copy the remainder of the data from my char* data beginning from an

最后...我如何正确计算 memcpy 中的“结束”参数?

这里是使用字符串的c++版本

char *insert = strstr(_in_mem_msg_ptr->buff(), "</body>");//get pointer to </body>
string ad_data = string(_in_mem_msg_ptr->buff(),insert - _in_mem_msg_ptr->buff()) ;//insert the part of _in_mem_msg_ptr->buff() before the </body>
ad_data.append(ad_content); //add the new html content
ad_data.append(_in_mem_msg_ptr->buff(),insert- _in_mem_msg_ptr->buff(),_in_mem_msg_ptr->dataLen()); //remainder of _in_mem_msg_ptr->buff() from and including </body> to the end

最佳答案

假设 char* original 由两部分组成,一部分从 0 开始,而另一部分(之后的 html 内容)从 x 开始你可以使用 strcat memcpy:

int length = strlen(original)+strlen(newcontent)+1;
char *neworiginal = malloc(sizeof(char)*length);
memset(neworiginal, 0, length);
memcpy(neworiginal,original,x*sizeof(char));
strcat(neworiginal,newcontent);
strcat(neworiginal,original+x);

关于c++ - 在 C 中修改一个 char* 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668091/

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