Home
Aptitude
Categories


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?





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.