Hope that the following code will give you an idea of how to do things..
You want to create a string with the first and last name of a person.
Thats how you may do it mate:
Code:
#include <stdio.h>
#include <stdlib.h>
char *Interesection(char *string1, char* string2)
{
if(string1 && string2)
{
int i;
int j = 0;
//For the given exercise we apply a space between the two strings so + 1 for the space, + 1 for the '\0' = +2
char *interS = (char *)calloc(strlen(string1) + strlen(string2) + 2, sizeof(char));
if(interS)
{
for(i = 0; i < strlen(string1); interS[j++] = string1[i], i++);
interS[j++] = ' ';
for(i = 0; i < strlen(string2); interS[j++] = string2[i], i++);
//Remember that the interesection of two stings will have max the sum of the strlen characters + 1 for space
//and string[j] will show the '\0' meaning we have strlen(string1) + strlen(string2) + 2 characters.
if(j == strlen(string1) + strlen(string2)+1)
{
interS[j] = '\0';
return interS;
}
else
{
free(interS);
return NULL;
}
}
else
{
printf("Memory Error.\n");
return NULL;
}
}
else
{
printf("NULL strings.\n");
return NULL;
}
}
int main(int argc, char *argv[])
{
char string1[80] = "Cristiano";
char *string2 = "Ronaldo";
char *r = NULL;
r = Interesection(string1, string2);
printf("%s\n", r);
//Strcat does the trick but it gives no space between the strings, and need the destination first string to be large
//enough to hold the result.
strcat(string1, string2);
printf("%s\n", string1);
system("PAUSE");
return 0;
}
Printed Results..
Cristiano Ronaldo
CristianoRonaldo
Press any key to continue . . .
Hope i helped..