22.5 — std::string assignment and swapping

String assignment

The easiest way to assign a value to a string is to use the overloaded operator= function. There is also an assign() member function that duplicates some of this functionality.

string& string::operator= (const string& str)
string& string::assign (const string& str)
string& string::operator= (const char* str)
string& string::assign (const char* str)
string& string::operator= (char c)

  • These functions assign values of various types to the string.
  • These functions return *this so they can be “chained”.
  • Note that there is no assign() function that takes a single char.

Sample code:

std::string sString;

// Assign a string value
sString = std::string("One");
std::cout << sString << '\n';

const std::string sTwo("Two");
sString.assign(sTwo);
std::cout << sString << '\n';

// Assign a C-style string
sString = "Three";
std::cout << sString << '\n';

sString.assign("Four");
std::cout << sString << '\n';

// Assign a char
sString = '5';
std::cout << sString << '\n';

// Chain assignment
std::string sOther;
sString = sOther = "Six";
std::cout << sString << ' ' << sOther << '\n';

Output:

One
Two
Three
Four
5
Six Six

The assign() member function also comes in a few other flavors:

string& string::assign (const string& str, size_type index, size_type len)

  • Assigns a substring of str, starting from index, and of length len
  • Throws an out_of_range exception if the index is out of bounds
  • Returns *this so it can be “chained”.

Sample code:

const std::string sSource("abcdefg");
std::string sDest;

sDest.assign(sSource, 2, 4); // assign a substring of source from index 2 of length 4
std::cout << sDest << '\n';

Output:

cdef

string& string::assign (const char* chars, size_type len)

  • Assigns len characters from the C-style array chars
  • Throws an length_error exception if the result exceeds the maximum number of characters
  • Returns *this so it can be “chained”.

Sample code:

std::string sDest;

sDest.assign("abcdefg", 4);
std::cout << sDest << '\n';

Output:

abcd

This function is potentially dangerous and its use is not recommended.

string& string::assign (size_type len, char c)

  • Assigns len occurrences of the character c
  • Throws a length_error exception if the result exceeds the maximum number of characters
  • Returns *this so it can be “chained”.

Sample code:

std::string sDest;

sDest.assign(4, 'g');
std::cout << sDest << '\n';

Output:

gggg

Swapping

If you have two strings and want to swap their values, there are two functions both named swap() that you can use.

void string::swap (string& str)
void swap (string& str1, string& str2)

  • Both functions swap the value of the two strings. The member function swaps *this and str, the global function swaps str1 and str2.
  • These functions are efficient and should be used instead of assignments to perform a string swap.

Sample code:

std::string sStr1("red");
std::string sStr2("blue");

std::cout << sStr1 << ' ' << sStr2 << '\n';
swap(sStr1, sStr2);
std::cout << sStr1 << ' ' << sStr2 << '\n';
sStr1.swap(sStr2);
std::cout << sStr1 << ' ' << sStr2 << '\n';

Output:

red blue
blue red
red blue
guest
Your email address will not be displayed
Find a mistake? Leave a comment above!
Correction-related comments will be deleted after processing to help reduce clutter. Thanks for helping to make the site better for everyone!
Avatars from https://gravatar.com/ are connected to your provided email address.
Notify me about replies:  
31 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
vstar

哈哈看来你的头发一定非常“茂密”

learnccp lesson reviewer

W LESSON

learnccp lesson reviewer

Best tutorial ever, I'll be donating a "few" thousand bucks when I get a job. Your effort is immensely appreciated Alex.

Emeka Daniel

:), awesome stuff

Waldo

These apply to this and future lessons in this chapter:

  • Missing std:: prefixes
  • endl
  • Direct initialization

Yup, definitely outdated. It's incredible how much the website has improved elsewhere, though!

Armitage

Why string& string::assign (const char* chars, size_type len) is potentially dangerous?

Blake

Please, make a chapter on maps. Learning from your lessons are the most easiest to understand.

yeokaiwei

Dear Alex,
With regards to swapping, we learned how to use a, b and temp variable for swapping. However, it is known to be inefficient. There are 2 other methods like arithmetic and bitwise XOR swapping, each with their own limitations. E.g. Arithmetic will overflow if anyone of the numbers are large and XOR'ing same numbers will return 0.

Could you point out the most efficient swapping method that is currently in use?

yeokaiwei

"_CONSTEXPR20 void swap(_Ty& _Left, _Ty& _Right) noexcept(
    is_nothrow_move_constructible_v<_Ty>&& is_nothrow_move_assignable_v<_Ty>) {
    _Ty _Tmp = _STD move(_Left);
    _Left    = _STD move(_Right);
    _Right   = _STD move(_Tmp);
}"

Hi Alex,
I think there is no difference. At the lowest level, swapping still uses the a,b,c(temp) method. The other methods are unstable and flawed.

Alek

hey, I tried to compile and run the following program but why do I get the latest char instead of the first one ?shouldn't it cout the first char it encounters ?

#include<iostream>
#include<string>

int main(){
std::string myStr;
myStr ='119';
std::cout<<myStr;
}

thanks!

Jestin PJ
#include<iostream>
#include<string>

int main(){
std::string myStr;
myStr =static_cast<char>(119);
std::cout<<myStr<<std::endl;
}
nascardriver

Character literals with more than 1 character have an implementation-defined (Differs between compilers) value, don't use them.

awdawewwsd

This is a question on chapter 15.
Instead of using std::weak_ptr, couldn't you use a normal pointer?