Written by Sai Sandeep Thota on April 6, 2013 in C++ > Programming

C++ Program to Join and Reverse Two Strings

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this article we will be dealing with Joining & Reversing two strings in C++. Who would like to write long code when there are predefined functions in the library? That’s what we have done here. So getting to the program we have defined a class with three character pointers and three size variables of integer data type. We have also defined three functions called setdata, rev, display for doing some operations.

So starting with setdata function, We are taking the input from the user and passing them to the function and then after passing the user given strings to the function we are copying the strings to our string variables defined in string class. We are using strcpy() to copy the strings and strcat() to concatenate or join the strings.

We came across a new term here new char[var] What does this mean? We have already created variables called size1, size2, size3 right? We are storing the length of strings in those variables and with the help of new datatype[size-variable], we are allotting the size to the string variable.

rev function is used to reverse the given string, we are using strrev() for reversing the string.

display function is used to display the given Strings and Joined strings.

In main function we are getting the Strings from the user and passing them to setdata function.

Join and Reverse two Strings using Dynamic Memory Allocation

#include<conio.h>
#include<iostream.h>
#include<string.h>

class string {
	char *s1, *s2, *s3;
	int size1, size2, size3;
	public:
	void setdata(char *, char *);
	void rev();
	void display();
};

void string::setdata(char *str1, char *str2) {
	/* Copy String1 */
	size1=strlen(str1);
	s1=new char[size1];
	strcpy(s1,str1);

	/* Copy String2 */
	size2=strlen(str2);
	s2=new char[size2];
	strcpy(s2,str2);

	/* Concatenate Two Strings */
	size3=size1+size2;
	s3=new char[size3];
	s3=strcat(str1,str2);
}

void string::display() {
	cout<<"\nString 1 is:"<<s1;
	cout<<"\nString 2 is:"<<s2;
	cout<<"\nJoined String is:"<<s3;
}

void string::rev() {
	cout<<"\nReverse of String 1 is:"<<strrev(s1);
	cout<<"\nReverse of String 2 is:"<<strrev(s2);
}

void main() {
	string ob;
	clrscr();

	char *string1, *string2;

	cout<<"\nEnter First String:";
	cin>>string1;

	cout<<"\nEnter Second String:";
	cin>>string2;

	ob.setdata(string1,string2);
	ob.display();
	cout<<"\n\n";
	ob.rev();
	getch();
}

Output:
Join-two-strings

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: