Erases a sequence of n characters starting at positionpos. Notice that both parameters are optional: with only one argument, the function deletes everything from positionpos forwards, and with no arguments, the function deletes the entire string, like memberclear.
iterator erase ( iterator position );
Erases the character referred by the iterator position. Only one character is affected.
// string::erase
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string str ("This is an example phrase.");
string::iterator it;
// erase used in the same order as described above:
//删除从位置10(从0开始算的,T为第一个位置0)开始的e之后的8个字符"example "
str.erase (10,8);
cout << str << endl; // "This is an phrase."
Searches the string for the content specified in eitherstr,s or c, and returns the position of the first occurrence in the string.
When pos is specified the search only includes characters on or after positionpos, ignoring any possible occurrences in previous locations.
Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that only one of these characters match, but the entire sequence of characters to find must be matched.
// string::find
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string str ("There are two needles in this haystack with needles.");
string str2 ("needle");
size_t found;
// different member versions of find in the same order as above:
found=str.find(str2);
if (found!=string::npos)
cout << "first 'needle' found at: " << int(found) << endl;
//从原字符串str的14+1 =15的位置之后开始查找,查找目标字串needles are small的首6个字符,找到位置即第44个位置。返回found = 44
found=str.find("needles are small",found+1,6);
if (found!=string::npos)
cout << "second 'needle' found at: " << int(found) << endl;
found=str.find("haystack");
if (found!=string::npos)
cout << "'haystack' also found at: " << int(found) << endl;
found=str.find('.');
if (found!=string::npos)
cout << "Period found at: " << int(found) << endl;
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
cout << str << endl;
return 0;
}
Notice how parameter pos can be used to search for a second instance of the same search string. Output:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.