Simple examples of using strcat to join two strings together in C
The most common example you will find on the internet will work by just making an array that is "big enough" to store both the strings. However this can create problems when the strings you use are too long so it would need these conditions handled correctly in C. So it probably isn't the best example to use.
void basic(char *s1, char *s2)
{
char str[200] = "";
strcat(str, s1);
strcat(str, s2);
printf("basic: %s\n", str);
}
A better example of using strcat is to allocate an array dynamically. In this case on the stack. So this will work slightly better however it can cause a significant amount of stack space to be used and can also cause crashes if the strings are too long. However it will execute very quickly because dynamic allocation of memory on the stack will perform well.
void better1(char *s1, char *s2)
{
char str[strlen(s1) + strlen(s2) * sizeof(*s1) + 1];
str[0] = '\0';
strcat(str, s1);
strcat(str, s2);
printf("basic: %s\n", str);
}
A much better example of this is to use malloc / free for the allocation of string. This will be slightly slower than the previous example but will be able to handler much larger strings and much safer to use. It can of course still crash but only if the machine run's out of memory. How ever this error can be handled to prevent it crashing by changing the call to abort() to use proper error handling.
void better2(char *s1, char *s2)
{
char *str = malloc(strlen(s1) + strlen(s2) + 1 * sizeof(*s1));
if (str == NULL)
abort();
str[0] = '\0';
strcat(str, s1);
strcat(str, s2);
printf("basic: %s\n", str);
free(str);
}
Finally this is an example about joining multiple strings so we can just keep making our string longer and longer or join it from multiple different sources. Note that the following code really needs a check around the realloc function to see if it returns NULL. If it does then it should fail by returning the previous pointer. Or call abort because the system has run out of memory.
char *multiple(char *str, char *s2)
{
int len;
char *s;
if (str != NULL)
len = strlen(str);
len += strlen(s2) + 1 * sizeof(*s2);
s = realloc(str, len);
strcat(s, s2);
return s;
}
With the above code we can call it in the following way
char *tmp = multiple(NULL, "Hello ");
tmp = multiple(tmp, " World");
tmp = multiple(tmp, " We");
tmp = multiple(tmp, " Can");
tmp = multiple(tmp, " Join");
tmp = multiple(tmp, " strings");
printf("%s\n", tmp);
free(tmp);
Did You find this page useful?
Yes
No