Program to concatenate two strings without using library function in C

Source Code

// 55.ii. Program to concatenate two strings without using library function
// Arpan Das - CST 2nd Year (VOCLET)

#include <stdio.h>
//#include <conio.h>

int strlength(char *);
void strcatenate(char *, char *);

void main () {
	char str1[50], str2[50];
	//clrscr();

	printf("\t\t..:: concatenate two strings without using library function ::..\n\n");
	printf("\nEnter string 1: ");
	scanf("%[^\n]%*c", str1); // String include spaces
	printf("\nEnter string 2: ");
	scanf("%[^\n]%*c", str2); // String include spaces

	strcatenate(str1, str2);
	printf("\n\n%s", str1);

	//getch();
}

int strlength(char *s) {
	int i=0, len=0;
	while (s[i++] != '\0') len++;
	return len;
}

void strcatenate (char *str1, char *str2) {
	int i, len = strlength(str1);

	for (i=0; i<strlength(str2); i++)
		str1[i+len] = str2[i];

	str1[i+len] = '\0';
}

	//  3    5
	// 012 01234
	// 012 34567
	// and phone
	/*len = strlength(str1);
	for (i=0; i<strlength(str2); i++)
		str1[i+len] = str2[i];

	str1[i+len] = '\0';*/

Output

	..:: concatenate two strings without using library function ::..

Enter string 1: Hi

Enter string 2: Jack

HiJack

Leave a Reply

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