Concatenation is a process of linking two more strings together in a chain-like structure to form a bigger string. There are multiple ways of concatenating strings and here we are going to discuss all of them one by one with C++ example code.
In C++, we work with two different kinds of strings one is a C-type string which is also known as Character Array and another is a String Class and we have different methods to concatenate these strings. If you are not familiar with the difference between Character Array and String Class then you can check out our post Character Array Vs String Class in C++.
Concatenate String Class Objects.
Using + operator:
We can concatenate two strings easily just by using the simple '+' operator between two strings and it will return us a single concatenated string.
C++ Example Code:
//C++ example program Concatenation two string #include<iostream> #include<string> using namespace std; int main(){ string leftstr = "Welcome to "; string rightstr = "AlgoLesson"; //concatenation string resultstr = leftstr + rightstr; cout<<resultstr<<endl; //leftstr = leftstr + rightstr leftstr += rightstr; cout<<leftstr<<endl; return 0; }
Welcome to AlgoLesson Welcome to AlgoLesson
string str1 = "Hello"; string str2 = "World";
//OK concatenate successfully
string str3 = str1 + " AlgoLesson " + str2;
//Error - cannot add two string literals
string str4 = "Wrong" + "Concatenation";
//OK - Code execute from left to right
string str5 = str1 + " Wrong" + " Concatenation";
//Error - One side of + operator must be a string type.
string str5 = "Wrong" + " Concatenation " + str1;
Using append() string function:
//C++ program Concatenation two string using append() #include<iostream> #include<string> using namespace std; int main(){ string first = "Hello"; string second = "World"; first.append(second); cout<<first<<endl; return 0; }
HelloWorld
Concatenation C-type string (Character Array).
//C++ program Concatenation C-type string #include<iostream> #include<cstring> using namespace std; int main(){ char str1[10] = "Learning"; char str2[10] = "Coding"; strcat(str1, str2); cout<<str1<<endl; return 0; }
LearningCoding
Note: C-type string does not support the use of operators on string that's one of the reason we cannot use + operator to concatenate two C-type or Character type string in C++. (alert-success)
No comments:
Post a Comment