Essentials Flashcards
A character in a string can be assigned. If userString is “abcde”, then userString.at(3) = ‘X’
yields “abcXe”.
at(): The notation someString.at(x) accesses the character at
index x of a string.
example syntax:
cout «_space;userWord.at(3);
Determining the last character in a string is often useful. If a string’s length is known, the last character is at index length - 1. Ex: “Hey” has length 3, with y at index 2. The function s1.size() returns
s1’s length. Ex: If s1 is “Hey”, s1.size() returns 3.
A common task is to append (add to the end) a string to an existing string. The function s1.append(s2) appends
string s2 to string s1. Ex: If s1 is “Hey”, s1.append(“!!!”) makes s1 “Hey!!!”.
find(item, indx) starts at index indx.
// userText is “Help me!”
userText.find(‘p’) // Returns 3
userText.find(‘e’) // Returns 1 (first occurrence of e only)
userText.find(‘z’) // Returns string::npos
userText.find(“me”) // Returns 5
userText.find(‘e’, 2) // Returns 6 (starts at index 2)
find(item) returns index of first item occurrence, else returns string::npos (a constant defined in the string library). Item may be char, string variable, string literal (or char array).
find(item, indx) starts at index indx.
substr(index, length) returns
substring starting at index and having length characters.
// userText is “http://google.com”
userText.substr(0, 7) // Returns “http://”
userText.substr(13, 4) // Returns “.com”
userText.substr(userText.size() - 4, 4) // Last 4: “.com”
A vector is
an ordered list of items of a given data type. Each item in a vector is called an element. A programmer must include the statement #include at the top of the file when planning to use vectors.
A programmer commonly needs to maintain a list of items, just as people often maintain lists of items like a grocery list or a course roster.
push_back()
push_back(c)
appends character c to the end of a string.
// userText is “Hello”
userText.push_back(‘?’); // Now “Hello?”
userText.size(); // Returns 6