Home »
C++ STL
String Assignment | C++ STL
String Assignment in C++ STL (Standard Template Library): In this article, we are going to learn how to assign a string in C++ STL and how to concatenate the strings?
Submitted by IncludeHelp, on August 19, 2018
In C++ STL, with "string" class, we can assign, replace string by using assignment operator (=), there is no more need to using strcpy() to assign the string after the declaration.
How to assign/replace the string?
Use assignment operator (=)
Syntax:
string_object = "string_value"
Note: we can also assign a single character to the string.
Example:
//declaration
string str;
//assignment
str = "Hello world!"
Program:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
//declare string object
string str;
//assign string
str = "Hello World!";
//print string
cout<< "str: " <<str<<endl;
//replace i.e. re-assign string again
str = "How are you?";
//print string
cout<< "str: " <<str<<endl;
//assign single character
str = 'H';
cout<< "str: " <<str<<endl;
return 0;
}
Output
str: Hello World!
str: How are you?
str: H
Concatenate string and assignment
Yes, we can concatenate two strings by using plus (+) operator and assign it to the string.
Example:
Input:
str1: Hello world,
str2: How are you?
Concatenation:
str3 = str1+ str2
Output:
str3: Hello world, How are you?
Program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare string objects
string str1, str2, str3;
//assign the strings
str1 = "Hello world";
str2 = "How are you?";
//concatenate str1, str2 along with space and assign to str3
str3 = str1 + ' ' + str2;
//print the string values
cout<< "str1: " << str1 <<endl;
cout<< "str2: " << str2 <<endl;
cout<< "str3: " << str3 <<endl;
return 0;
}
Output
str1: Hello world
str2: How are you?
str3: Hello world How are you?