Contact Learn C
Copy

Program 89:To concatenate two strings

Program 89:
 
#include<stdio.h>
#include<string.h>
main()
{
int i,j=0,len;
char str1[100],str2[100];
printf("Enter string 1\n");
gets(str1);
printf("Enter string 2 \n");
gets(str2);

for(i=0;str1[i]!='\0';i++);

str1[i]=' ';
i++;
for(j=0;str2[j]!='\0';j++,i++)
{
    str1[i]=str2[j];
}
str1[i]='\0';
printf("%s\n",str1);

}
Explanation:

  1. This program starts with initializing :
    • i,j → used as helping variable
    • str1 → To store input from user
    • str2 → To store output of program
    • len To store length of string
  2. printf("Enter string 1\n");
    gets(str1);
    printf("Enter string 2 \n");
    gets(str2);
    Taking string 1 and 2 from user for concatenation. 
  3. for(i=0;str1[i]!='\0';i++);
    While concatenation we should add the string 2 at the end of string 1.So in order to do that we need to go to the end of string 1('\0'). As We do not know the string length we need to traverse from 0 to end of the string 1.The above forloop will get us to the end of str1 as it won't do any operation except moving from 0th character to '\0'(end of string).
    str1[i]=' ';
    i++;
    For example we have str1 as "hello" so the loop will traverse from 0 to 4 as 4 is length of string. As the loop will end at i=5 so we use this i=5 for removing '\0' and we kept a space instead by str[5]=' '; and then the next string str2 has to be added from i=6 which is why we used i++ So str2 will be added to str1 from 6th position. 
  4. *-There is another way to avoid traversing by keeping a loop.
    We can use len=strlen(str1) and by using str[len]=' ';and the i=len+1 instead of forloop.
  5. for(j=0;str2[j]!='\0';j++,i++)
    {
        str1[i]=str2[j];
    }
    here the str2 will be added from str1[6].For example str2 is "world" then it will be stored from str1[6] till str[10]
    str1[i]='\0';
    To add str[11] as the end of string. 
  6. printf("%s\n",str1);
    Finally to print string 1.And the output will be "hello world"
 Output:

To concatenate two strings
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide