This blog is under construction

Monday, 24 June 2013

C program to concatenate two strings without using library function

Write a C program to concatenate two strings without using built-in function(strcat).


  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  int main() {
        char str1[64], str2[64], *str3, i = 0, j = 0;

        /* get the first i/p string from user */
        printf("Enter your 1st string:");
        fgets(str1, 64, stdin);
        str1[strlen(str1) - 1] = '\0';

        /* get the second i/p string from user */
        printf("Enter your 2nd string:");
        fgets(str2, 64, stdin);
        str2[strlen(str2) - 1] = '\0';

        /* allocate memory for the sum of size of above two i/p strings */
        str3 = (char *)malloc(strlen(str1) + strlen(str2));

        /* store the first string in str3 */
        while (str1[i] != '\0') {
                str3[i] = str1[i];
                i++;
        }

        /* append the second string with str3 */
        while (str2[j] != '\0') {
                str3[i] = str2[j];
                i++;
                j++;
        }
        str3[i] = '\0';

        /* display the concatenated string */
        printf("Result: %s\n", str3);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your 1st string:Hello
  Enter your 2nd string:World
  Result: HelloWorld



No comments:

Post a Comment