String assignment
The easiest way to assign a value to a string is to the 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)
Sample code:
string sString;
// Assign a string value
sString = string("One");
cout << sString << endl;
const string sTwo("Two");
sString.assign(sTwo);
cout << sString << endl;
// Assign a C-style string
sString = "Three";
cout << sString << endl;
sString.assign("Four");
cout << sString << endl;
// Assign a char
sString = '5';
cout << sString << endl;
// Chain assignment
string sOther;
sString = sOther = "Six";
cout << sString << " " << sOther << endl;
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)
Sample code:
const string sSource("abcdefg");
string sDest;
sDest.assign(sSource, 2, 4); // assign a substring of source from index 2 of length 4
cout << sDest << endl;
Output: cdef |
string& string::assign (const char* chars, size_type len)
Sample code:
string sDest;
sDest.assign("abcdefg", 4);
cout << sDest << endl;
Output: abcd This function is potentially dangerous and it’s use is not recommended. |
string& string::assign (size_type len, char c)
Sample code: string sDest; sDest.assign(4, 'g'); cout << sDest << endl; 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)
Sample code:
string sStr1("red");
string sStr2("blue);
cout << sStr1 << " " << sStr2 << endl;
swap(sStr1, sStr2);
cout << sStr1 << " " << sStr2 << endl;
sStr1.swap(sStr2);
cout << sStr1 << " " << sStr2 << endl;
Output: red blue blue red red blue |
17.6 — std::string appending
|
Index
|
17.4 — std::string character access and conversion to c-style strings
|
17.6 — std::string appending
Index
17.4 — std::string character access and conversion to c-style strings
[...] 17.5 — std::string assignment and swapping [...]
[...] 17.5 — std::string assignment and swapping [...]
string sStr1("red"); string sStr2("blue); cout << sStr1 << " " << sStr2 << endl; swap(sStr1, sStr2); cout << sStr1 << " " << sStr2 << endl; sStr1.swap(sStr2); cout << sStr1 << " " << sStr2 << endl;from last code block u forgot to close “blue with …”…
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.
[...] 17.5 — std:string assignment and swapping [...]
[...] =, assign() +=, append(), push_back() insert() clear() erase() replace() resize() swap() [...]