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)
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)
Sample code: Output: cdef |
string& string::assign (const char* chars, size_type len)
Sample code: Output: abcd This function is potentially dangerous and its use is not recommended. |
string& string::assign (size_type len, char c)
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)
Sample code: Output: red blue blue red red blue |