Method prototype/operator | Explanation | Example |
---|---|---|
string() | default constructor; creates an empty string | string str1; |
= | assign a string to this string | str1 = str2 |
= | assign an array to this string | str1 = "help" |
>> | extraction operator; ignores leading whitespace and extracts and stores characters until whitespace is found | cin >> str1 |
<< | insertion operator | cout << str1 |
void getline(istream& iStr, string& str) | extracts and stores all characters, including whitespace, from the stream,iStr, through the next newline (\n) character. The newline character is extracted but not stored. If a newline character is found, the extracted characters are stored in str. If not, i.e. iStr.eof() is true, then str is not changed. Note that this is not a member function so the dot(.) operator is not used. | getline(cin, str1) |
void getline(istream& iStr, string& str, char delimiter) | extracts and stores all characters, including whitespace, from the stream,iStr, through the next delimiter. The delimiter is extracted but not stored. If a delimiter character is found, the extracted characters are stored in str. If not, i.e. iStr.eof() is true, then str is not changed. Note that this is not a member function so the dot(.) operator is not used. | getline(cin,str1,':') |
== | equality operator | str1 == str2 |
!= | inequality operator | str1 != str2 |
< | less than operator | str1 < str2 |
<= | less than or equal operator | str1 <= str2 |
> | greater than operator | str1 > str2 |
>= | greater than or equal operator | str1 >= str2 |
int length() | returns the number of characters in this string | i = str1.length() |
char& at(int pos) | returns the character at position pos. Remember that strings start at position 0! This is an l-value, that is, it can be used on the left hand side of an assignment statement. | c = str1.at(5) str1.at(5) = 't' |
int find(const string& str) | returns the position of the first occurrence of str in this string. Returns string::npos if str is not found. | i = str1.find(str2) |
string& insert(int start, const string& str) | insert str into this string starting at position start | str1.insert(5,str2) |
string& erase(int start, int n) | erase the next n characters from this string starting at position start | str1.erase(5,8) |
string& replace(int start, int n, const string& str) | replace the next n characters, starting at position start, with str. | str1.replace(5,6,str2) |
string& assign(const string& str) | assign str to this string | str1.assign(str2) |
string& assign(const string& str, int start, int n) | this string becomes the substring of str, starting at position start and n characters long. | str1.assign(str2,5,6) |
+ | return the concatenated string | str1 + str2; str1 + "tion"; "con" + str1; str1 + 'h'; 'u' + str1; |