I have this:
char* original = \"html content\";
And want to insert a new
char* mycontent = \"newhtmlinsert\";
You need to use strcat()
for this problem.
Example =
/* strcat example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
Though you need to check the bounds so you can use the bounds variant of strncat()
.
#include <string.h>
char *strncat(char *restrict s1, const char *restrict s2, size_t n);
Make sure whatever buffer you are appending your string into has enough space to not cause a buffer overflow.
Take a look at strstr, strcat and other cstring/string.h functions.
Make sure your char
arrays are large enough to hold concatenated strings. Like, you may want to do the following:
char neworiginal[1024];
etc.
The string.h
function strcat
will concatenate two strings, however it will fail when there is not enough space for the new string. My solution is to make your own version of strcat
:
char* myStrCat(const char* str1, const char* str2)
{
char* result;
char* itr1;
char* itr2;
if (str1 == NULL || str2 == NULL)
{
return NULL;
}
result = (char*)malloc(sizeof(char) * (strlen(str1) + strlen(str2) + 1));
itr1 = result;
itr2 = (char*)str1;
while (*itr2 != '\0')
{
*itr1 = *itr2;
itr1++;
itr2++;
}
itr2 = (char*)str2;
while (*itr2 != '\0')
{
*itr1 = *itr2;
itr1++;
itr2++;
}
*itr1 = '\0';
return result;
}
This is kinda ugly, but it gets the job done :)
C++ doesn't have + operator for char * strings. You need to use std::string, i.e.
std::string neworiginal = "html content before </body>";
neworiginal += "newhtlminsert";
neworiginal += "..."
Assuming that char* original
is composed by two parts, one starts at 0 while the other (html content after) starts at x
you can use strcat
and 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);
Attempting to modify the contents of a string literal results in undefined behavior.
You will need to allocate a target buffer (either as an auto variable or by using malloc
) that's large enough to hold your final string plus a 0 terminator.
Also, you might want to use sprintf
to make life a little easier, such as
sprintf(result, "%s before %s - %s - %s after %s", original,
tag, mycontent, original, tag);