beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C Program to concatenate two strings without using strcat

By Chaitanya Singh | Filed Under: C Programs

In the following program user would be asked to enter two strings and then the program would concatenate them. For concatenation we have not used the standard library function strcat(), instead we have written a logic to append the second string at the end of first string.

C program for string concatenation

/* C program to concatenate two strings without
 * using standard library function strcat()
 */
#include <stdio.h>
int main()
{
   char str1[50], str2[50], i, j;
   printf("\nEnter first string: ");
   scanf("%s",str1);
   printf("\nEnter second string: ");
   scanf("%s",str2);
   /* This loop is to store the length of str1 in i
    * It just counts the number of characters in str1
    * You can also use strlen instead of this.
    */
   for(i=0; str1[i]!='\0'; ++i); 
 
   /* This loop would concatenate the string str2 at
    * the end of str1
    */
   for(j=0; str2[j]!='\0'; ++j, ++i)
   {
      str1[i]=str2[j];
   }
   // \0 represents end of string
   str1[i]='\0';
   printf("\nOutput: %s",str1);
   
   return 0;
}

Output:
string_concat
As you can see we have entered two strings and in the output of the program both the strings got concatenated.

Enjoyed this post? Try these related posts

  1. C Program to find largest element of an Array
  2. C Program to find greatest of three numbers
  3. C Program to Find the Largest of three numbers using Pointers
  4. Hello World Program in C
  5. C Program to check if a number is palindrome or not
  6. C Program to display Fibonacci series

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap