string Library Quick Reference


string OperationDescription
string aString; Declare aString as an empty string
string aString = "hi"; Declare aString as a non-empty string
cin >> aString; Read a word from cin, storing it in aString
cout << aString; Display via cout the string within aString
getline(cin, aString); Read a line from cin, storing it in aString
aString[i] Access the character in aString whose index is i
aString.size() Determine the number of characters in aString
aString.substr(pos,size) Access the substring of aString consisting of size characters, starting at index pos
aString.replace(pos,size,newString); Replace size characters in aString with newString, starting at index pos
aString.erase(pos,size); Remove size characters from aString, starting at index pos
aString.insert(pos,newString); Insert newString into aString, starting at index pos
aString.find(pattern, pos) Determine the index at which pattern begins within aString, searching forward from pos
aString.rfind(pattern, pos) Determine the index at which pattern begins within aString, searching backward from pos
aString.find_first_of(pattern, pos) Determine the first index at which any character in pattern occurs within aString, by searching forward from pos
aString.find_last_of(pattern, pos) Determine the last index at which any character in pattern occurs within aString, by searching backward from pos
string1 == string2 Equality relational comparison
string1 != string2 Inequality relational comparison
string1 < string2 Less-than relational comparison
string1 > string2 Greater-than relational comparison
string1 <= string2 Less-than-or-equal relational comparison
string1 >= string2 Greater-than-or-equal relational comparison
string1 = string2; Make string1 a copy of string2
string1 + string2 Create a new string consisting of string1 followed by string2
string1 += string2; Append string2 to string1

For each of the "find" functions, if the item being sought is not present in the string, the function returns string::npos, a special constant defined in the string library.


Back to The Lab Exercise

Back to the Table of Contents


Report all errors to Larry Nyhoff (nyhl@cs.calvin.edu)