Reputation: 7353
i use strcat()
to connect two strings like:
#include <string.h>
#include <stdio.h>
int main(int argc, char *args[])
{
char *str1; // "456"
char *str2; // "123"
strcat(str1,str2);
printf("%s",str1);
}
i get:
456123
but i need the second string on beginning of first string like:
123456
how can i do it ?
Upvotes: 5
Views: 37015
Reputation: 36
If you only want to add a single char :
char *add_char_to_beginning(char c, char **str)
{
char *tmp = strdup(*str);
*str = (char *) realloc(*str, sizeof(char) * (strlen(*str) + 2));
*(str[0]) = c;
strcpy(*str + 1, tmp);
free(tmp);
return *str;
}
Upvotes: 0
Reputation: 36
If you segfault on this because you have two non-allocated strings with different sizes, maybe it'll solve the probleme. I first calculated the size difference to allocate the first string with the bigger size (in which [padding] will be concatenated at the begining). Then added the code of @Rohan.
if (len1 < len2) {
char *tmp = strdup(num1);
num1 = (char *) malloc(sizeof(char) * (strlen(num1) + diff));
strcpy(num1, padding);
strcat(num1, tmp);
printf("%s\n", num1);
free(tmp);
}
Upvotes: 0
Reputation: 421
try to use this with static sized arrays, works for me in my project.
void strbeg(char* strReceive, char* strInsert)
{
int strInsertLength = strlen(strInsert);
int strReceiveLength = strlen(strReceive);
for(int i = strReceiveLength; i >= 0; i--)
{
strReceive[i + strInsertLength] = strReceive[i];
}
for(int i = 0; i < strInsertLength; i++)
{
strReceive[i] = strInsert[i];
}
}
Upvotes: 1
Reputation: 70981
Verbatim from man strcat
:
char *strcat(char *dest, const char *src);
DESCRIPTION
The strcat() function appends the src string to the dest string, overwriting the null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result.
As the programmer you need to make sure that the pointer char * dest
references enough valid memory to hold the addtional char
s that will be copied from where char* src
points to.
To succesfully prefix str1
with str2
declare them as follows:
char str2[3 + 1] = "123"; // three for "123" plus 1 for the terminating 0
char str1[2 + 3 + 1] = "46"; // 2 for "46" plus 3 for "123" plus 1 for the terminating zero
to actually concatenate the two char
arrays do so:
strcat(str1, str2);
Upvotes: 0
Reputation: 53386
Do strcat(str2,str1);
, switch the parameters. But you will get resultant string in str2
, which you can set to str1
if you really want to use str1
further in your program.
However, you need to take care appropriately for memory space available in str2
.
If you want to change str1
then, do this
char *tmp = strdup(str1);
strcpy(str1, str2); //Put str2 or anyother string that you want at the begining
strcat(str1, tmp); //concatenate previous str1
...
free(tmp); //free the memory
Upvotes: 7