Write a C++ program which take two strings as input from user and concatenate two strings without using the string class function strcat(). Keep the order as first come first and second comes second after concatenation.
This c++ tutorial covers following concepts
C++ program source code
Program output
see also: count number of vowels in arrays
concatenate two strings using strcat string class function
More examples: C++ programming examples
This c++ tutorial covers following concepts
- while loop
- char array
- if statement
How c++ program works
- There are total 3 strings two for input and third for our result. Each string has fixed size you may change as your requirement.
- There are two index variables both initialized by zero at the beginning of program to get access the index value of both strings
- There are two while loops in the program runs till null not found in both string.
- Using index we start read first string from zero index and write its value to resultant string same with the second while loop where we keep increment the index variable value and access second string by the use of index2 variable.
- At the end we use for loop variable to show result.
C++ program source code
#include <iostream>
using namespace std;
int main()
{
int index = 0;
int index2 = 0;
const int SIZE = 10;
char firstStringObj[SIZE], secondStringObj[SIZE], concatString[50]={'0'};
cout<<"Enter first String: ";
cin>>firstStringObj;
cout<<"Enter second String: ";
cin>>secondStringObj;
while(firstStringObj[index] != '\0') {
concatString[index] = firstStringObj[index];
index++;
}
while(secondStringObj[index2] != '\0') {
index++;
concatString[index] = secondStringObj[index2];
index2++;
}
cout<<"\n\n\nConcatenated String: ";
for(int j=0;j<SIZE+SIZE;j++)
cout<<concatString[j];
cout<<"\n\n\n";
return 0;
}
Program output
see also: count number of vowels in arrays
concatenate two strings using strcat string class function
More examples: C++ programming examples
Just use the + operator man
ReplyDeleteLiterally one line
string1 + string2
When this type of question is given to students they are not taught about string variables and they are not allowed to use those because that will make things much more easy and they will not learn the hard work
Delete