1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 int main() 6 { 7 string s("hello"); 8 string s2("abcdef"); 9 10 string::iterator p = s.begin(); 11 cout << *p << endl; 12 s.insert(p, ‘A‘); //插入之后,p指向新插入的数据 13 cout << *p << endl; 14 cout << s << endl; 15 16 //每执行插入操作一次,gcc下必须重新给迭代器赋值 17 //否则内存泄漏 18 // 为什么呢?不明白 19 p = s.begin(); 20 s.insert(p,‘B‘); 21 cout << *p << endl; 22 cout << s << endl; 23 24 string::iterator b = s2.begin(); 25 string::iterator e = s2.end(); 26 27 p = s.begin(); 28 s.insert(p, b, e); 29 cout << s << endl; 30 31 s = "hello"; 32 cout << s <<endl; 33 s.assign(b, e); 34 cout << s <<endl; 35 36 s.assign(8, ‘k‘); 37 cout << s <<endl; 38 39 s = "abcdef"; 40 p = s.begin(); 41 s.erase(p); //删除 42 cout << s <<endl; 43 44 p = s.begin(); 45 p++; 46 p++; 47 string::iterator p2 = s.end(); 48 p2--; 49 s.erase(p, p2); 50 cout << s <<endl; 51 52 s = "hello"; 53 s2 = "abc"; 54 s.insert(0, 3, ‘A‘); 55 cout << s <<endl; 56 57 s.insert(5, s2); //位置从0开始,第6个元素之前 58 cout << s <<endl; 59 60 s2 = "12345"; 61 s.insert(0, s2, 2, 3); 62 cout << s <<endl; 63 64 char *cp = "Stately plump Buck"; 65 s.assign(cp, 7); 66 cout << s <<endl; 67 s.assign(cp); 68 cout << s <<endl; 69 70 s = "hello"; 71 s.insert(0, cp, 7); 72 cout << s <<endl; 73 s = "hello"; 74 s.insert(0, cp); 75 cout << s <<endl; 76 77 s = "hello"; 78 s2 = "abcdef"; 79 s.assign(s2, 2, 3); 80 cout << s << endl; 81 82 s.erase(2, 3); 83 cout << s <<endl; 84 85 s = "123456789"; 86 s.erase(s.size()-5, 1); //删除字符串的倒数第5个; 87 cout << s <<endl; 88 89 s.insert(s.size(), 5, ‘!‘); //size()最后一个的后一个,insert在size()之前插入; 90 cout << s <<endl; 91 92 s = "abc"; 93 s.erase(0, 1).insert(0, "A"); 94 cout << s <<endl; 95 96 s = "abc"; 97 s[0] = ‘A‘; 98 cout << s <<endl; 99 return 0; 100 } 101
时间: 2024-12-28 01:00:28