ADVERTISEMENT
ADVERTISEMENT

C program to concatenate two strings without using library function

In this program, we will learn how to concatenate or add two strings without using library function? Here we are implementing a function like strcat() that will add two strings.

The function stringCat() will be used in this program to concatenate two strings, where strings will be read by the user.

Program to concatenate/add two strings without using library function in C

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
 
 
/********************************************************
    *   function name       :stringCat
    *   Parameter           :char* s1,char* s2
    *   Return              :void
    *   Description         :Concatenate  two strings
********************************************************/
void stringCat (char *s1,char *s2);
 
 
int main()
{
    char str1[MAX_SIZE],str2[MAX_SIZE];

    printf("Enter  string 1 : ");
    scanf("%[^\n]s",str1);//read string with spaces
 
	getchar();//read enter after entering first string
 
    printf("Enter  string 2 : ");
    scanf("%[^\n]s",str2);//read string with spaces
 
    stringCat(str1,str2);
    printf("\nAfter concatenate strings are :\n");
    printf("String 1: %s \nString 2: %s",str1,str2);
 
    printf("\n");
    return 0;
}
 
/******** function definition *******/
void stringCat (char *s1,char *s2)
{
    int len,i;
    len=strlen(s1)+strlen(s2);
    if(len>MAX_SIZE)
    {
        printf("\nCan not Concatenate !!!");
        return;
    }
     
    len=strlen(s1);
    for(i=0;i< strlen(s2); i++)
    {
        s1[len+i]=s2[i];
    }
    s1[len+i]='\0'; /* terminates by NULL*/
}

Output

Enter  string 1 : Hello
Enter  string 2 : Friends

After concatenate strings are :
String 1: HelloFriends
String 2: Friends

C Strings User-defined Functions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.