Search

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:

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:

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:

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:

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:

Output:

red blue
blue red
red blue


22.6 -- std::string appending
Index
22.4 -- std::string character access and conversion to C-style arrays

21 comments to 22.5 — std::string assignment and swapping

  • 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 ?

    thanks!

  • awdawewwsd

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

  • “is to the use the”, probably “is to use the”…

  • apfelpektin

    quote from above:

    does anybody have some more information what that is about? it seems not to be the case here. double and single quotes for example are copied correctly from a string literal.

  • Matt

    Above section Swapping", you wrote:
    "Throws an length_error exception...".

    "an" should be "a".

  • Sheeplie

    If the string& string::operator= (const string& str) requires a constant string argument, how are you simply able to do

    ?

    • Sheeplie

      After refreshing myself on function parameters, I've deduced that this is possible because a function parameter is it's own new variable inside of a function, simply given the value of whatever argument you pass in. So you could make it constant, sure- it's its own variable, and that const var would simply receive the value of string( "one") ( which it would reference. )

    • Alex

      The compiler will convert const literal string "One" into a "string" object via converting constructor std::string(const char*).

      In other words, the compiler is smart enough to know how to convert "One" into a std::string because there's a std::string constructor that takes C-style string literals.

  • Lokesh

    Last code, line 2: missing <">

  • Benjamin

    In the line 2 of the sample code of Swapping section :
    Close the quotation after the word 'blue' otherwise the code would not run in the way that which is intended for.
    Good Day.

  • Matt

    Typo ("it's" should be "its"): "This function is potentially dangerous and it’s use is not recommended."

  • Aryan

    Hey Alex,

    I just want to ask a simple question. We know that the input stream (cin>>) its terminated after it sees a whitespace. But what if I want to include in my sting type object (lets say string name) a whole sentence? Like in my 'name' variable I store a string of characters "Hello how are you", but if I did this:

    string name;
    cin>>name; // I wrote 'Hello how are you'

    So how will win take action on this when it sees a whitespace after 'Hello', will it terminate and won't store the rest of the string?

  • abcd

    Hi Alex,

    Thanks a lot for these wonderful tutorials. Can you please add some tutorials on Vector, other Container classes, Shared_ptr, and other advanced C++ topics?

    Thanks a lot again.

  • ap

    from last code block u forgot to close "blue with ..."...

Leave a Comment

Put all code inside code tags: [code]your code here[/code]