#include <iostream> #include <string> using namespace std; int main() { string str = "to be question"; string str2 = "the "; string str3 = "or not to be"; string::iterator it;
//s.insert(pos, str)//在s的pos位置插入str str.insert(6, str2); // to be the question
//s.insert(pos, str, a, n)在s的pos位置插入str中插入位置a到后面的n个字符 str.insert(6, str3, 3, 4); // to be not the question
//s.insert(pos, cstr, n)//在pos位置插入cstr字符串从开始到后面的n个字符 str.insert(10, "that is cool", 8); // to be not that is the question cout << str << endl;
//s.insert(pos, cstr)在s的pos位置插入cstr str.insert(10, "to be "); // to be not to be that is the question
//s.insert(pos, n, ch)在s的pos位置上面插入n个ch str.insert(15, 1, ':'); // to be not to be: that is the question
//s.insert(s.it, ch)在s的it指向位置前面插入一个字符ch,返回新插入的位置的迭代器 it = str.insert(str.begin() + 5, ','); // to be, not to be: that is the question
//s.insert(s.it, n, ch)//在s的it所指向位置的前面插入n个ch str.insert (str.end(), 3, '.'); // to be, not to be: that is the question...
//s.insert(it, str.ita, str.itb)在it所指向的位置的后面插入[ita,itb)的字符串 str.insert (it+2, str3.begin(), str3.begin() + 3); // to be, or not to be: that is the question...
#include <iostream> #include <string> using namespace std; int main () { string base = "this is a test string."; string str2 = "n example"; string str3 = "sample phrase"; string str4 = "useful.";
string str = base; // "this is a test string." cout << str << endl;
#include <iostream> #include <string> using namespace std; int main() { string str ("There are two needles in this haystack with needles."); string str2 ("needle");
// different member versions of find in the same order as above: //在str当中查找第一个出现的needle,找到则返回出现的位置,否则返回结尾 int found = str.find(str2); if (found != string::npos) cout << "first 'needle' found at: " << found << '\n';
//在str当中,从第found+1的位置开始查找参数字符串的前6个字符 found = str.find("needles are small", found + 1, 6); if (found != string::npos) cout << "second 'needle' found at: " << found << '\n';
//在str当中查找参数中的字符串 found = str.find("haystack"); if (found != string::npos) cout << "'haystack' also found at: " << found << '\n';
//查找一个字符 found = str.find('.'); if (found != string::npos) cout << "Period found at: " << found << '\n';
//组合使用,把str2用参数表中的字符串代替 // let's replace the first needle: str.replace(str.find(str2), str2.length(), "preposition"); cout << str << '\n';
return 0; }
输出结果为:
4.3.2 rfind
rfind函数就是找最后一个出现的匹配字符串,返回的位置仍然是从前往后数的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream> #include <string> using namespace std; int main() { string str ("The sixth sick sheik's sixth sheep's sick."); string key ("sixth");// ^ //rfind是找最后一个出现的匹配字符串 int found = str.rfind(key); if (found != string::npos) { cout << found << endl; //输出23 str.replace (found,key.length(),"seventh"); //找到的sixth替换成seventh } cout << str << '\n'; return 0; }