Problem & Solution
In this C Program we have to accept two strings from user using gets and we have to concatenate these two strings without using library functions.
C Program
#include<stdio.h> #include<string.h> void concat(char[], char[]); int main() { char s1[50], s2[30]; printf("\nEnter String 1 :"); gets(s1); printf("\nEnter String 2 :"); gets(s2); concat(s1, s2); printf("\nConcated string is :%s", s1); return (0); } void concat(char s1[], char s2[]) { int i, j; i = strlen(s1); for (j = 0; s2[j] != '\0'; i++, j++) { s1[i] = s2[j]; } s1[i] = '\0'; }
Output
The above code sample will produce the following result.
Enter String 1 : Ankit Enter String 2 : Singh Concated string is : AnkitSingh
Explanation of Program
Step 1. input
let two string variable s1 and s2 having input
s1 = “Ankit”;
s2 = “Singh”;
Step 2. Found Last position
Then found length of first string
= strlen(s1);
= strlen(“Ankit”);
= 5
Last position of s1 = 5
STEP 3. Concatenat
Now we can Concatenat second string using for loop
s1[5] = “S”
s1[6] = “i”
s1[7] = “n”
s1[8] = “g”
s1[9] = “h”