Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcat paste second string at beginning of first string

Tags:

c

string

strcat

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 ?

like image 459
Refael Avatar asked Jan 13 '23 07:01

Refael


2 Answers

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
like image 118
Rohan Avatar answered Jan 16 '23 19:01

Rohan


Try sprintf() to print the new value to the first string

sprintf(str1,"%s%s",str2,str1);
like image 31
adazem009 Avatar answered Jan 16 '23 18:01

adazem009