Method prototype/operator | Explanation | Example |
---|---|---|
string() | default constructor; creates an empty string | string str1; |
= | assign a string to this string | str1 = str2 |
= | assign a character 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 or end of file whichever comes first. The newline character is extracted but not stored. The extracted characters are stored in str. It returns true if successful. 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 or end of file whichever comes first. The delimiter is extracted but not stored. The extracted characters are stored in str. It returns true if successful. 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! If pos is not a valid position, the program will Abort at runtime. 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' |
[ ] | same as at except that the index is not checked. | c = str1[5]; str1[5] = 't'; |
+ | return the concatenated string | str1 + str2; str1 + "tion"; "con" + str1; str1 + 'h'; |
+= | append a string or character to this string | str1 += str2; str1 += "tion"; str1 += 'h'; |